【发布时间】:2012-09-05 13:15:13
【问题描述】:
我正在用 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?假设我将在多处理器环境中运行此代码。
【问题讨论】:
-
void ThreadWorkerClass() => 这应该是构造函数吗?然后你只创建一个对象,线程数永远不会超过 1。
-
感谢@PermanentGuest,已编辑代码。
-
为什么不在
for循环中创建 20 个线程并保留它? -
@DavidSchwartz 是的,这是我也在考虑的第二种方法,除了这个设计。类似于拥有一个常量 ThreadPool 和一个将提交任务/作业的公共队列。
-
@AakashRoy - 大卫的评论/答案是最好的。如果您可以避免线程微管理,那么您绝对应该这样做。如果您无法避免线程微管理,请更改您的设计,直到您可以
标签: c++ multithreading boost static static-members