你可以使用障碍。
来自randu.org's pthread tutorial 的 pthread Barriers 部分:
pthreads 可以参与一个屏障来同步到某个时间点。屏障对象像互斥锁或条件变量一样被初始化,除了有一个额外的参数 count。 count 变量定义了必须加入屏障的线程数,以使屏障完成并解除阻塞在屏障处等待的所有线程。
换句话说,您可以使用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