首页 > 解决方案 > 如何在线程池中正确分配 pthread 空闲状态?

问题描述

我正在使用下面的代码来创建一个线程池,但是我找不到合适的地方来设置线程空闲状态,如何修改下面的代码以便我可以拿起哪个线程忙?

std::vector<structThread> preallocatedThreadsPool;
std::queue<int> tcpQueue;
struct structThread {
    pthread_t thread;
    bool idleState;
};
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condition_var = PTHREAD_COND_INITIALIZER;

void* threadFunctionUsedByThreadsPool(void *arg);
std::atomic<bool> stopCondition(false);



main () {
   preallocatedThreadsPool.resize(preallocatThreadsNumber); // create a threadpoOl.           
     for(structThread &i : preallocatedThreadsPool) {
         pthread_create(&i.thread, NULL, threadFunctionUsedByThreadsPool, NULL);
     }
       

  // when a event happened
  pthread_mutex_lock(&mutex); // one thread mess with the queue at one time
  tcpQueue.push(even);
  pthread_cond_signal(&condition_var);
  pthread_mutex_unlock(&mutex);

}


void* threadFunctionUsedByThreadsPool(void *arg) {
    pthread_mutex_lock(&mutex);
    while (!stopCondition) {
           // wait for a task to be queued
       while (tcpQueue.empty() && !stopCondition) {
           pthread_cond_wait(&condition_var, &mutex); // wait for the signal from other thread to deal with client otherwise sleep
       }
       if (stopCondition == false) {

           newevent = tcpQueue.front();
           tcpQueue.pop();
           pthread_mutex_unlock(&mutex);  // exit lock while operating on a task
           // do even related task
           pthread_mutex_lock(&mutex);  // re-acquire the lock
       }
 
    }
   // release the lock before exiting the function
   pthread_mutex_unlock(&mutex);
   return NULL;
}

上面的代码,每次从队列中弹出一个新的偶数时,我如何找到一种方法将相应线程的无遗嘱设置为忙?因为目前,每次有任务来,系统只是随机给我的线程池中的线程分配一个任务,如何修改代码让我的线程池可以记住每个线程的空闲状态

标签: c++multithreadingalgorithmpthreadsthreadpool

解决方案


上面的代码,每次从队列中弹出一个新的偶数时,我如何找到一种方法将相应线程的无遗嘱设置为忙?

这很容易:只需在您重新锁定互斥锁idleState = false之前设置pthread_mutex_unlock并返回(在事件相关代码完成之后)。true

因为目前,每次有任务来,系统只是随机分配一个任务给我的线程池中的线程

使用线程池的正确方法。您想做的任何其他事情都可能会添加错误。


推荐阅读