I work with 3 different threads (t0, t1 and t2), whom I need to synchronize behaviors this way:
My main thread will be creating these 3 threads, and those will be looping through prints and barrier just like I mentionned.
I tried to write the functions I pass them (f0 for t0, f1 for t1, etc.):
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);
}
}
It worked well till the first barrier is met, but it looked like the barrier was not resetting, I tried to re-init once al threads came across it but it had weird effects.
#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;
}
This produces the wanted output.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.