pthread conditional variable

后端 未结 5 1527
借酒劲吻你
借酒劲吻你 2020-12-14 05:16

I\'m implementing a thread with a queue of tasks. As soon as as the first task is added to the queue the thread starts running it.

Should I use pthread condition var

5条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-14 05:47

    Semaphores are good if-and-only-if your queue already is thread safe. Also, some semaphore implementations may be limited by top counter value. Even it is unlikely you would overrun maximal value.

    Simplest and correct way to do this is following:

    pthread_mutex_t queue_lock;
    pthread_cond_t  not_empty;
    queue_t queue;
    
    push()
    {
      pthread_mutex_lock(&queue_lock);
      queue.insert(new_job);
      pthread_cond_signal(¬_empty)
      pthread_mutex_unlock(&queue_lock);
    }
    pop()
    {
      pthread_mutex_lock(&queue_lock);
      if(queue.empty()) 
         pthread_cond_wait(&queue_lock,¬_empty);
      job=quque.pop();
      pthread_mutex_unlock(&queue_lock);
    }
    

提交回复
热议问题