我正在开发一个使用多线程来模拟人和电梯的程序。有一部电梯,多人乘坐电梯。
到目前为止,我正在尝试为每个人创建一个线程,并为电梯创建一个线程。然而,人们需要等待电梯被创建才能开始执行他们的操作,而电梯需要等待所有的人被创建才能开始移动。
我研究了 pthread_join(),但看起来它等待线程完成,这不是我想要的。
最佳答案
您可以使用障碍。
来自 randu.org's pthread tutorial 的 pthread Barriers 部分:
pthreads can participate in a barrier to synchronize to some point in time. Barrier objects are initialized like mutexes or condition variables, except there is one additional parameter, count. The count variable defines the number threads that must join the barrier for the barrier to reach completion and unblock all threads waiting at the barrier.
换句话说,您可以使用 n
创建屏障,并且任何调用 pthread_barrier_wait
的线程都将等待,直到 n
次调用 pthread_barrier_wait
已完成。
下面是一个简单的示例,其中所有三个线程都将在任何线程打印“After”之前打印“Before”。
#include <pthread.h>
#include <stdio.h>
pthread_barrier_t barrier;
void* foo(void* msg) {
printf("%s: before\n", (char*)msg);
// No thread will move on until all three threads have reached this point
pthread_barrier_wait(&barrier);
printf("%s: after\n", (char*)msg);
}
int main() {
// Declare three threads
int count = 3;
pthread_t person_A, person_B, elevator;
// Create a barrier that waits for three threads
pthread_barrier_init(&barrier, NULL, count);
// Create three threads
pthread_create(&person_A, NULL, foo, "personA");
pthread_create(&person_B, NULL, foo, "personB");
pthread_create(&elevator, NULL, foo, "elevator");
pthread_join(person_A, NULL);
pthread_join(person_B, NULL);
pthread_join(elevator, NULL);
printf("end\n");
}
运行代码here
关于c - 如何让多个 POSIX 线程等待另一个线程开始,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53125648/