【问题标题】:pthread and synchronizationpthread 和同步
【发布时间】:2013-06-19 16:57:00
【问题描述】:

我有一个关于多线程同步的问题。 我们假设我们有 2 个 pthread 和一个 fifo 队列。 线程 1 将在此队列中插入元素,线程 2 将从同一队列中提取这些元素。 我实现了我的队列的两个操作:push 和 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);

}

thread2 就会有这个生命周期:

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

}

这段代码会导致死锁的情况吗? 在等待之前,我必须解锁互斥锁吗?

【问题讨论】:

标签: c++ pthreads signals mutex deadlock


【解决方案1】:

没有可见的死锁。

pthread_cond_wait() 隐式释放互斥锁。

但是,您可以将 pthread_mutex_unlock() 移到 pthread_cond_signal() 之前调用。

【讨论】:

  • 为了更清楚,它会在等待期间释放它,并在返回之前重新获取它。
  • 是的,当然,感谢您添加此内容,事实上,这是pthread_cond_wait() 行为的重要组成部分。
  • 不,你不应该在信号之前移动解锁,因为它不会给你买任何东西并且会降低性能(stackoverflow.com/a/6312416/768469
猜你喜欢
  • 1970-01-01
  • 2012-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-07
  • 2021-12-02
相关资源
最近更新 更多