我正在使用单独的类,c ++标准库deques和Linux上的boost线程来创建一个简单的线程生成器/使用者示例。我通过引用将共享缓冲区,锁定和条件变量作为成员变量传递给我的类。线程启动正常,但由于锁定断言错误,通常会在随机时间崩溃。
main: ../nptl/pthread_mutex_lock.c:80: __pthread_mutex_lock: Assertion `mutex->__data.__owner == 0' failed.
以下是我在主
中启动主题的方法std::deque<double> buf;
boost::condition_variable_any buf_has_space;
boost::condition_variable_any buf_has_data;
boost::mutex buf_lock;
boost::thread producerThread(load_func, &buf, &buf_has_space, &buf_has_data, &buf_lock);
boost::thread consumerThread(consume_func, &buf, &buf_has_space, &buf_has_data, &buf_lock);
producerThread.join();
consumerThread.join();
producerThread
和consumerThread
初始化并运行myProducer
和myConsumer
的实例。
来自myProducer
的相关代码:
void myProducer::add_to_buffer(){
//Main loop
for (int i=0; i<100000; i++){
boost::mutex::scoped_lock lock(*buffer_lock);
while (buffer->size() == max_size){
buffer_has_space->wait(*buffer_lock);
}
buffer->push_back(i);
buffer_has_data->notify_one();
buffer_lock -> unlock();
}
//Consumer will stop when it sees -1
boost::mutex::scoped_lock lock(*buffer_lock);
while (buffer->size() == max_size){
buffer_has_space->wait(*buffer_lock);
}
buffer->push_back(-1.0);
buffer_has_data->notify_one();
buffer_lock -> unlock();
}
来自myConsumer
的相关代码:
void myConsumer::load_from_buffer(){
double current = 0;
while (current != -1.0) {
boost::mutex::scoped_lock lock(*buffer_lock);
while (buffer->size() == 0){
buffer_has_data->wait(*buffer_lock);
}
current = buffer->front();
buffer->pop_front();
buffer_has_space->notify_one();
buffer_lock->unlock();
std::cout << current <<"\n";
}
}
我看过这些问题:
pthread_mutex_lock.c:62: __pthread_mutex_lock: Assertion `mutex->__data.__owner == 0' failed
但是,在我的类被解构之前程序崩溃了,并且每个锁都与同一个线程中的解锁相匹配。
答案 0 :(得分:2)
如果您拥有锁定保护(scoped_lock)所拥有的锁定,则手动操作锁定会出错。
如果必须在范围结束前操纵锁定,您可以在scoped_lock
本身上执行此操作:
lock.unlock(); // instead of buffer_lock -> unlock();