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

标签 c++ multithreading boost static static-members

我正在用 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
  }
};

所以一切都由池类在内部维护。永远不要把那个类(class)的控制权交给其他人。您还可以向池类添加查询函数,如 hasFreeThreads()、numFreeThreads() 等...

您还可以通过提供智能指针来 boost 此设计,这样您就可以了解有多少人仍然拥有该线程。 让获得线程的人负责释放它有时是危险的,因为进程崩溃并且他们永远不会返回线程,有很多解决方案,最简单的方法是在线程用完时在每个线程上维护一个时钟被强行收回。

关于c++ - C++ 中线程计数的静态类变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12282301/

相关文章:

python - 如何减少过滤文章数据集的时间?

c++ - 需要为 C++ std::vector 编写共享内存分配器

c++ - 了解编译顺序、编译错误和由于基类未定义而导致的 luabind

c++ - 更改后如何将默认名称设置为窗口?

c++ - 在 C++11 中, "does not represent a thread of execution"的线程有什么意义?

c++ - GMainLoop 和 TCP Listen 线程阻塞

c++ - 带有 std::map 错误函数调用的 boost::factory

c++ - 使用 boost 库从文件创建图形

c++ - 将 QThread 移动到另一个线程?

qt - 为每个 Qt Kit 指定 boost 库