我使用 3 个不同的线程(t0、t1 和 t2),我需要以这种方式同步它们的行为:
我的主线程将创建这 3 个线程,这些线程将循环遍历打印和屏障,就像我提到的那样。
我尝试编写传递给它们的函数(f0 代表 t0,f1 代表 t1 等):
pthread_barrier_t b; //in my main I initialize pthread_barrier_init(&b, NULL, 3);
void *f0(void *arg){
while(1){
printf("A\n");
pthread_barrier_wait(&b);
pthread_barrier_wait(&b);
printf("D\n");
}
}
void *f1(void *arg){
while(1){
pthread_barrier_wait(&b);
printf("B\n");
pthread_barrier_wait(&b);
}
}
void *f2(void *arg){
while(1){
pthread_barrier_wait(&b);
printf("C\n");
pthread_barrier_wait(&b);
}
}
它运行良好,直到遇到第一个障碍,但看起来障碍没有重置,我尝试在所有线程遇到它时重新初始化,但它产生了奇怪的效果。
最佳答案
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
pthread_barrier_t b[2];
pthread_t t[3];
void *f0(void *arg){
while(1){
printf("A");
pthread_barrier_wait(&b[0]);
pthread_barrier_wait(&b[1]);
printf("B\n");
sleep(1);
}
}
void *f1(void *arg){
while(1){
pthread_barrier_wait(&b[0]);
printf("C");
pthread_barrier_wait(&b[1]);
}
}
void *f2(void *arg){
while(1){
pthread_barrier_wait(&b[0]);
printf("D");
pthread_barrier_wait(&b[1]);
}
}
void *(*f[3])(void*) = {&f0, &f1, &f2};
int main(){
for(int barrier = 0; barrier < 2; barrier++){
if(pthread_barrier_init(&b[barrier], NULL, 3) != 0){
perror("pthread_barrier_init");
return 1;
}
}
for(int thread = 0; thread < 3; thread++){
if(pthread_create(&t[thread], NULL, f[thread], NULL) != 0){
perror("pthread_create");
return 2;
}
}
for(int thread = 0; thread < 3; thread++){
if(pthread_join(t[thread], NULL) != 0){
perror("pthread_join");
return 3;
}
}
return 0;
}
这会产生所需的输出。
关于c - 循环线程中的 pthread_barrier_t,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58579688/