Reputation: 41
Hi I am trying to make 3 thread that will print different messages multiple times. Then sync them, so to print for example ONE TWO THREE ONE TWO THREE ONE TWO THREE... When I run the program sometimes it is not correct and I am not sure what I am doing wrong.
sem_t sema, semb, semc;
void *printone(void *arg)
{
printf("<ONE>");
sem_wait(&semc);
sem_post(&semb);
}
void *printtwo(void *arg)
{
printf("<TWO>");
sem_wait(&sema);
sem_post(&semc);
}
void *printthree(void *arg)
{
printf("<THREE>");
sem_wait(&semb);
sem_post(&sema);
}
main()
{
pthread_t th1,th2,th3;
int i;
sem_init(&sema,0,1);
sem_init(&semb,0,0);
sem_init(&semc,0,0);
for(i=0;i<10;i++){
pthread_create( &th1, NULL, printone, (void *) 1);
pthread_create( &th2, NULL, printtwo, (void *) 2);
pthread_create( &th3, NULL, printthree, (void *) 3);
pthread_join(th1, NULL);
pthread_join(th2, NULL);
pthread_join(th3, NULL);
}
pthread_exit(NULL);
}
Upvotes: 0
Views: 288
Reputation: 180058
You seem to have a workable approach: each thread waits on one semaphore, and later posts another to let the next thread run. For that to work, however, each thread should wait for its semaphore before performing its work (i.e. print its message).
Additionally, it looks like your thread functions are using the wrong semaphores. For printone()
to run first, it must wait on the semaphore that you initialize with value 1. For printtwo()
to run next, it must wait on whichever semaphore printone()
posts to. Similarly, for printthree()
.
As a secondary matter, if your thread functions are not going to use their argument, then it would be best to pass NULL
as the third argument to pthread_create()
.
Upvotes: 1