简体   繁体   中英

Sync threads with Posix Semaphores

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);

}

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 (ie 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() .

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM