c++ - 如何在线程池中正确分配 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;
}
上面的代码,每次从队列中弹出一个新的偶数时,我如何找到一种方法将相应线程的无遗嘱设置为忙?因为目前,每次有任务来,系统只是随机给我的线程池中的线程分配一个任务,如何修改代码让我的线程池可以记住每个线程的空闲状态
解决方案
上面的代码,每次从队列中弹出一个新的偶数时,我如何找到一种方法将相应线程的无遗嘱设置为忙?
这很容易:只需在您重新锁定互斥锁idleState = false
之前设置pthread_mutex_unlock
并返回(在事件相关代码完成之后)。true
因为目前,每次有任务来,系统只是随机分配一个任务给我的线程池中的线程
这是使用线程池的正确方法。您想做的任何其他事情都可能会添加错误。
推荐阅读
- javascript - UnhandledPromiseRejectionWarning: TypeError: object is not iterable... 当使用 await Promise.all(promises);
- postgresql - Postgres 的 Adventureworks 数据库
- unix - 在unix中将一列拆分为一行并提取选择性数据
- java - Spring注解/记录spring自定义事件的方法
- node.js - Azure - 持续运行 WebJob:支持 Node.JS 和文档
- angular - 角度无法将条纹导入组件
- flutter - 如何在颤振中使用共享偏好?
- python-3.x - 如何使用 Python 根据 Shapefile 裁剪任何图像?
- swift - SwiftUI Apple Watch 应用程序在发布版本时崩溃(仅限系列 3)
- python-3.x - 如何在 Prefect 中只执行一次任务?