C++中线程计数的静态类变量

Static Class variable for Thread Count in C++

本文关键字:静态 静态类 类变量 线程 C++      更新时间:2023-10-16

我正在用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()等…

你也可以通过提供智能指针来增强这种设计,这样你就可以跟踪有多少人仍然拥有这个线程。让获得线程的人负责释放它有时是危险的,因为进程崩溃,他们永远不会后退,对此有很多解决方案,最简单的是在每个线程上保持一个时钟,当时间用完时,线程会被强制收回。