【发布时间】:2010-08-24 00:18:24
【问题描述】:
我已经编写了我自己的线程安全队列版本。但是,当我运行这个程序时,它会自行挂起/死锁。
想知道,为什么这会永远锁定/挂起。
void concurrentqueue::addtoQueue(const int number)
{
locker currentlock(lock_for_queue);
numberlist.push(number);
pthread_cond_signal(&queue_availability_condition);
}
int concurrentqueue::getFromQueue()
{
int number = 0;
locker currentlock(lock_for_queue);
if ( empty() )
{
pthread_cond_wait(&queue_availability_condition,&lock_for_queue);
}
number = numberlist.front();
numberlist.pop();
return number;
}
bool concurrentqueue::empty()
{
return numberlist.empty();
}
我写过,类储物柜为 RAII。
class locker
{
public:
locker(pthread_mutex_t& lockee): target(lockee)
{
pthread_mutex_lock(&target);
}
~locker()
{
pthread_mutex_unlock(&target);
}
private:
pthread_mutex_t target;
};
我的写/读线程代码非常简单。写线程,加入队列,读线程,从队列中读取。
void * writeintoqueue(void* myqueue)
{
void *t = 0;
concurrentqueue *localqueue = (concurrentqueue *) myqueue;
for ( int i = 0; i < 10 ; ++i)
{
localqueue->addtoQueue(i*10);
}
pthread_exit(t);
}
void * readfromqueue(void* myqueue)
{
void *t = 0;
concurrentqueue *localqueue = (concurrentqueue *) myqueue;
int number = 0;
for ( int i = 0 ; i < 10 ; ++i)
{
number = localqueue->getFromQueue();
std::cout << "The number from the queue is " << number << std::endl;
}
pthread_exit(t);
}
【问题讨论】:
-
无论如何我都不是
pthreads专家,但我认为您不想将pthread_mutex_t按值复制到target中的locker课程中。将target设为pthread_mutex_t &或pthread_mutex_t *。 -
@spong 我确定这是问题所在。通过制作副本,锁定和信号不再处理相同的结构,这将导致许多 pthread 实现变得不稳定。您应该添加您的评论作为答案。
-
为什么要重新发明轮子。这是我使用的实现。 gist.github.com/482342
-
洛根先生,您说得对。感谢您解决问题。
-
Mr.Logan,我该如何给你的正确答案。您介意发布相同的答案,以便我可以选择您的答案。
标签: c++ multithreading stl pthreads