0

I have a question about muti threading synchronization.. We suppose that we have 2 pthread and an fifo queue. Thread 1 will insert the elements in this queue and thread 2 will extract these elements from the same queue. I implemented the two operations of my queue: push and pop.

void push(element e) {

pthread_mutex_lock(&mutex);
myVector.push_back(e);
pthread_cond_signal(&empty);
pthread_mutex_unlock(&mutex);

}

Element pop() {

pthread_mutex_lock(&mutex);
if(myVector.size() == 0) 
pthread_cond_wait(&empty, &mutex);
//extract the element from the queue;
pthread_mutex_unlock(&mutex);

}

the thread2 will then have this life cycle:

while(myBoolFlag) {
    Element theElement = myQueue->pop();
usleep(500000);

}

this code can lead to deadlock situations? before of wait, must I unlock the mutex?

Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129
Safari
  • 11,437
  • 24
  • 91
  • 191
  • 3
    It's fine, but you need to use `while` not `if` to check the predicate (see http://stackoverflow.com/q/6206350/768469) – Nemo Jun 19 '13 at 17:29

1 Answers1

0

No deadlocks visible.

pthread_cond_wait() implicitly releases the mutex.

However, you could move pthread_mutex_unlock() to be called before pthread_cond_signal().

alk
  • 69,737
  • 10
  • 105
  • 255
  • 1
    To be clearer, it releases it for the duration of the wait, and reacquires it prior to returning. – Dave S Jun 19 '13 at 17:29
  • Yes sure, thanks for adding this, in fact, essential part of `pthread_cond_wait()`'s behaviour. – alk Jun 19 '13 at 17:30
  • 1
    No, you should NOT move the unlock before the signal, because it buys you nothing and can cost performance (http://stackoverflow.com/a/6312416/768469) – Nemo Jun 19 '13 at 17:32