gpt4 book ai didi

c++ - pthread_cond_wait 和 pthread_mutex_lock 没有按预期工作

转载 作者:行者123 更新时间:2023-11-28 02:08:02 25 4
gpt4 key购买 nike

我已经创建了一个 ThreadPool 类和一个名为 execute_thread_helper() 的 void 函数,该函数在 void* execute_thread(void* arg) 中调用(它是给定的函数这样的线程:ret = pthread_create(&workers[i], NULL, execute_thread, (void*)this);)

void ThreadPool::execute_thread_helper()
{
Task task;

pthread_mutex_lock(&mutex);

while(TaskList.empty()) // Previously "if"
{
cout << "Thread #" << pthread_self() << " is blocked. "<< endl;
pthread_cond_wait(&conditionVar, &mutex);
}

task = TaskList.front();
TaskList.pop();

cout << "Thread #" << pthread_self() << " going to run the function. "<< endl;

threadFunction(task);

pthread_mutex_unlock(&mutex);
}

任务以这种方式添加到任务队列中 -

void ThreadPool::add_task(Task newTask)
{
pthread_mutex_lock(&mutex);

TaskList.push(newTask);
pthread_cond_signal(&conditionVar);

pthread_mutex_unlock(&mutex);

}

据我所知,一旦创建线程 - 它就会尝试运行 execute_thread。然后,给定一个空队列,我希望 pthread_cond_wait 将线程“置于”休眠状态(并对所有创建的线程执行此操作),直到它被 pthread_cond_signal添加任务

好吧..我尝试在单个线程上检查程序,并得到了这个结果(我没有add_task。只是尝试创建池)-

Thread #139859560904448 is blocked. 
Thread #139859560904448 going to run the function.
in map() key is and value is 0

我不明白线程是如何通过 if 语句的,如果它之前被搁置的话。

尝试创建 3 个线程池时的输出 -

Thread #140013458028288 is blocked. 
Thread #140013458028288 going to run the function.
in map() key is and value is 0
Thread #140013458028288 going to run the function.
in map() key is and value is 0
Thread #140013458028288 going to run the function.
in map() key is and value is 0

为什么其他 2 个线程没有被搁置?

编辑

感谢 SergeyA,将 if 与 while 切换,确实有所帮助。但是,仍然尝试创建 3 个线程池,结果是 -

Thread #139916558706432 is blocked. 
Thread #139916558706432 is blocked.
Thread #139916558706432 is blocked.
Thread #139916558706432 is blocked.
Thread #139916558706432 is blocked.
Thread #139916558706432 is blocked.
Thread #139916558706432 is blocked.
Thread #139916558706432 is blocked.

为什么没有创建其他线程?它们不是都应该被创建、同时运行并交替打印它们被阻止吗?

最佳答案

条件变量容易出现所谓的 *spurios 唤醒。这意味着代码已解锁,但条件并没有真正改变,也没有发出信号。

这就是为什么您总是必须在循环中调用wait 函数,并在每次唤醒后检查条件。

关于c++ - pthread_cond_wait 和 pthread_mutex_lock 没有按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36747518/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com