【发布时间】:2020-11-15 16:03:46
【问题描述】:
我正在使用下面的代码创建一个线程池,但是我找不到合适的地方设置线程空闲状态,如何修改下面的代码以便我可以选择哪个线程忙?
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;
}
上面的代码,每次从队列中弹出一个新的偶数时,我如何找到一种方法将相应线程的无遗嘱设置为忙?因为目前,每次有任务来,系统只是随机给我的线程池中的线程分配一个任务,如何修改代码让我的线程池可以记住每个线程的空闲状态
【问题讨论】:
-
不要将任务分配给线程。将它们放在一个队列中,让线程在准备好后从队列中取出项目。
-
不要设置线程空闲状态。当线程空闲时,它应该等待。您可以为此使用 condition_var。我看到您正在将 POSIX/C 库与 C++ 混合使用。 C++ 有它自己的与 POSIX 接口的库,它更简单。看看我的例子:github.com/doa379/libqueue-
标签: c++ multithreading algorithm pthreads threadpool