【发布时间】:2020-11-13 22:19:15
【问题描述】:
我已经使用下面的结构创建了一个线程池,现在的问题是如何让所有预分配线程正确结束?
std::vector<pthread_t> preallocatedThreadsPool; // threadpool
std::queue<int> tcpQueue; // a queue to hold my task
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condition_var = PTHREAD_COND_INITIALIZER;
void* threadFunctionUsedByThreadsPool(void *arg);
main () {
preallocatedThreadsPool.resize(preallocatThreadsNumber);
for(pthread_t i : preallocatedThreadsPool) {
pthread_create(&i, NULL, threadFunctionUsedByThreadsPool, NULL);
}
pthread_mutex_lock(&mutex); // one thread mess with the queue at one time
tcpQueue.push(task);
pthread_cond_signal(&condition_var);
pthread_mutex_unlock(&mutex);
}
void* threadFunctionUsedByThreadsPool(void *arg) {
while (true) {
pthread_mutex_lock(&mutex);
if (tcpQueue.empty()) { // can't get work from the queue then just wait
pthread_cond_wait(&condition_var, &mutex); // wait for the signal from other thread to deal with client otherwise sleep
task = tcpQueue.front();
tcpQueue.pop();
}
pthread_mutex_unlock(&mutex);
if (task) {
// do task
}
}
return NULL;
}
我一直在寻找这个问题的日子仍然找不到一个像样的解决方案,我尝试过的最接近的一个是,当程序要退出时,将一个特殊项目推入队列,然后在 threadFunctionUsedByThreadsPool 中,当检测到这样的item,我会调用pthread_join,但是,当我使用gdb工具调试它时,那些预先分配的线程仍然存在,任何人都可以提供帮助,更好地使用一些代码,例如,我如何修改threadFunctionUsedByThreadsPool,以便我可以正确退出所有预先分配的线程? 非常感谢!!!
【问题讨论】:
-
您是否有意使用
pthread_create而不是C++ 线程? (即std::thread)?
标签: c++ multithreading server pthreads threadpool