我正在用C ++编写基于线程的应用程序。以下示例代码显示了我如何检查线程数。我需要确保在任何时间点,我的应用程序只生成了20个工作线程:
#include<stdio.h>
using namespace std;
class ThreadWorkerClass
{
private:
static int threadCount;
public:
void ThreadWorkerClass()
{
threadCount ++;
}
static int getThreadCount()
{
return threadCount;
}
void run()
{
/* The worker thread execution
* logic is to be written here */
//Reduce count by 1 as worker thread would finish here
threadCount --;
}
}
int main()
{
while(1)
{
ThreadWorkerClass twObj;
//Use Boost to start Worker Thread
//Assume max 20 worker threads need to be spawned
if(ThreadWorkerClass::getThreadCount() <= 20)
boost::thread *wrkrThread = new boost::thread(
&ThreadWorkerClass::run,&twObj);
else
break;
}
//Wait for the threads to join
//Something like (*wrkrThread).join();
return 0;
}
这个设计是否要求我锁定变量threadCount
?假设我将在多处理器环境中运行此代码。
答案 0 :(得分:3)
设计不够好。问题在于您暴露了构造函数,因此无论您是否喜欢它,人们都可以根据需要创建任意数量的对象实例。你应该做一些线程池。即,您有一个维护一组池的类,如果可用,它会提供线程。
之类的东西class MyThreadClass {
public:
release(){
//the method obtaining that thread is reponsible for returning it
}
};
class ThreadPool {
//create 20 instances of your Threadclass
public:
//This is a blocking function
MyThreadClass getInstance() {
//if a thread from the pool is free give it, else wait
}
};
所以一切都由汇集类在内部维护。永远不要把控制权交给其他人。您还可以向池类添加查询函数,如hasFreeThreads(),numFreeThreads()等...
您还可以通过提供智能指针来增强此设计,以便您可以跟踪仍有多少人拥有该线程。 让人们获得负责释放它的线程有时是危险的,因为进程崩溃并且他们从不退回,有很多解决方案,最简单的是在每个线程上保持时钟,当时间用完线程被强行收回。