简体   繁体   中英

Change the blocking behavior on sem_wait in pthread

I understand that when sem_wait(foo) is called, the caller enters block state if the value of foo is 0.

Instead of entering block state, I want to caller to sleep for a random period of time. Here is the code I've come up with.

/* predefined a semaphore foo with initial value of 10 */

void* Queue(void *arg)
{
   int bar;
   int done=0;
   while(done=0)
   {
      sem_getvalue(&foo,&bar);
      if(bar>0){
           sem_wait(&foo);
           /* do sth */
           sem_post(&foo);
           done=1;
      }else{ sleep(rand() % 60); }
   }
   pthread_exit(NULL);
}

How can I improve or is there any better solution to do this?

The code you have is racy: what if the semaphore goes to zero between the moment when you check it and the moment you do the sem_wait ? You'll be in the situation you want to avoid (ie thread blocked on the semaphore).

You could use sem_trywait instead, which will not block if the semaphore is at zero when you call it.

There's a reason such a call doesn't exist: there's no real point. If you're using multiple threads, and you need to do something else, use another thread. If you want to see if you can do something, use sem_trywait().

Also, the way you're using the semaphore in your example seems more suited to a mutex if you're using the code to limit the number of threads in the section to just one. And there's no real gain to limiting the number of threads in the section to any number greater than one because at that point the section has to be multithread-safe anyway.

Semaphores are more useful in a producer-consumer pattern.

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