【问题标题】:Static Class variable for Thread Count in C++C++中线程计数的静态类变量
【发布时间】: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


【解决方案1】:

设计不够好。问题是您暴露了构造函数,因此无论您喜欢与否,人们都可以根据需要创建任意数量的对象实例。你应该做某种线程池。即您有一个维护一组池的类,如果可用,它会发出线程。像

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() 等...

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

【讨论】:

    猜你喜欢
    • 2011-07-17
    • 2011-12-08
    • 2013-03-29
    • 1970-01-01
    • 2011-06-03
    • 2016-08-30
    • 1970-01-01
    • 1970-01-01
    • 2013-05-18
    相关资源
    最近更新 更多