C++中线程计数的静态类变量
Static Class variable for Thread Count in C++
我正在用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
吗?假设我将在多处理器环境中运行此代码。
设计不够好。问题是你公开了构造函数,所以不管你喜欢与否,人们都可以根据自己的意愿创建任意多的对象实例。你应该做一些线程池。即,您有一个维护一组池的类,如果可用,它会发出线程。类似的东西
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
}
};
所以所有的东西都是由pooling类内部维护的。永远不要把对那个阶级的控制权交给其他人。您还可以将查询函数添加到池类中,如hasFreeThreads()、numFreeThreads()等…
你也可以通过提供智能指针来增强这种设计,这样你就可以跟踪有多少人仍然拥有这个线程。让获得线程的人负责释放它有时是危险的,因为进程崩溃,他们永远不会后退,对此有很多解决方案,最简单的是在每个线程上保持一个时钟,当时间用完时,线程会被强制收回。
相关文章:
- 静态 constexpr 类成员变量对多线程读取是否安全?
- 我的编译器是否忽略了我未使用的静态thread_local类成员
- 静态存储类C++计数
- 内联初始化的静态 const 类成员的初始化顺序保证
- 继承:动态派生类成员与静态派生类成员
- 避免在静态常量类上定义但不使用
- 根据模板参数可以选择静态的类成员
- 为什么不允许静态成员变量的初始化在类中,而允许静态静态成员的初始化
- 子类中具有不同值的静态基类属性
- 等效于 Java 静态对象类C++
- 是否可以按模板类型更改静态 const 类成员的值
- 如何在标题和CPP之间拆分静态/模板类
- 静态模板类成员函数的这两个调用之间有什么区别?
- 对静态重载(类)函数/方法的调用是不明确的
- 具有静态模板类成员的模板类:如何定义静态成员
- pthread没有静态的类
- 单例文件静态与类私有静态
- 使用折叠表达式初始化静态 constexpr 类数据成员不编译
- constexpr静态结构类成员的声明冲突
- 初始化在 C++ 中自定义类的构造函数中没有参数的静态 const 类成员