简体   繁体   English

在pthread中更改sem_wait上的阻止行为

[英]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. 我了解,当sem_wait(foo)调用时,如果foo的值为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 ? 您拥有的代码很活泼:如果在您检查信号的时刻与执行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. 您可以改用sem_trywait ,如果调用时信号量为零,它将不会阻塞。

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(). 如果要查看是否可以执行某些操作,请使用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. 信号量在生产者-消费者模式中更有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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