【发布时间】:2021-10-30 15:56:09
【问题描述】:
我遇到了一个问题,我很难判断我应该使用哪个同步原语。
我正在创建 n 个在内存区域上工作的并行线程,每个线程都分配给该区域的特定部分,并且可以独立于其他线程完成其任务。在某些时候我需要收集所有线程的工作结果,这是使用障碍的一个很好的例子,这就是我正在做的事情。
我必须使用 n 个工作线程之一来收集他们所有工作的结果,为此我在线程函数中的计算代码后面有以下代码:
if (pthread_barrier_wait(thread_args->barrier)) {
// Only gets called on the last thread that goes through the barrier
// This is where I want to collect the results of the worker threads
}
到目前为止一切顺利,但现在我陷入困境:上面的代码处于循环中,因为我希望线程在一定数量的循环自旋中再次完成工作。这个想法是,每次pthread_barrier_wait 解除阻塞都意味着所有线程都完成了它们的工作,并且循环/并行工作的下一次迭代可以重新开始。
这样做的问题是结果收集器块语句不能保证在其他线程再次开始在该区域上工作之前执行,因此存在竞争条件。我正在考虑使用这样的 UNIX 条件变量:
// This code is placed in the thread entry point function, inside
// a loop that also contains the code doing the parallel
// processing code.
if (pthread_barrier_wait(thread_args->barrier)) {
// We lock the mutex
pthread_mutex_lock(thread_args->mutex);
collectAllWork(); // We process the work from all threads
// Set ready to 1
thread_args->ready = 1;
// We broadcast the condition variable and check it was successful
if (pthread_cond_broadcast(thread_args->cond)) {
printf("Error while broadcasting\n");
exit(1);
}
// We unlock the mutex
pthread_mutex_unlock(thread_args->mutex);
} else {
// Wait until the other thread has finished its work so
// we can start working again
pthread_mutex_lock(thread_args->mutex);
while (thread_args->ready == 0) {
pthread_cond_wait(thread_args->cond, thread_args->mutex);
}
pthread_mutex_unlock(thread_args->mutex);
}
这有多个问题:
- 出于某种原因,
pthread_cond_broadcast永远不会解锁等待pthread_cond_wait的任何其他线程,我不知道为什么。 - 如果一个线程
pthread_cond_waits 在收集器线程广播之后会发生什么?我相信while (thread_args->ready == 0)和thread_args->ready = 1可以防止这种情况发生,但请看下一点... - 在下一个循环旋转时,
ready仍将设置为1,因此没有线程将再次调用pthread_cond_wait。我看不到任何地方可以将ready正确设置回0:如果我在pthread_cond_wait之后的else 块中执行此操作,则有可能另一个没有等待条件的线程读取@987654335 @ 并开始等待,即使我已经从if块广播了。
请注意,我需要为此使用障碍。
我该如何解决这个问题?
【问题讨论】:
标签: c multithreading unix condition-variable barrier