0

我正在用 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?假设我将在多处理器环境中运行此代码。

4

1 回答 1

3

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

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

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

于 2012-09-05T13:22:18.667 回答