0

マルチスレッド同期について質問があります.2 つの pthread と fifo キューがあるとします。スレッド 1 はこのキューに要素を挿入し、スレッド 2 は同じキューからこれらの要素を抽出します。キューに push と pop という 2 つの操作を実装しました。

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

}

次に、thread2 のライフサイクルは次のようになります。

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

}

このコードはデッドロックの状況につながる可能性がありますか? 待機する前に、ミューテックスのロックを解除する必要がありますか?

4

1 に答える 1

0

デッドロックは見られません。

pthread_cond_wait()ミューテックスを暗黙的に解放します。

pthread_mutex_unlock()ただし、前に呼び出されるように移動することはできますpthread_cond_signal()

于 2013-06-19T17:27:24.533 に答える