C++ 互斥锁因无效参数而失败是什么意思?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30090108/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What does mutex lock fail with invalid argument mean?
提问by Ender
This code is called in my main process and compiles fine, but when executed always throws the error below.
这段代码在我的主进程中被调用并且编译得很好,但是在执行时总是会抛出下面的错误。
bounded_buffer<MyData> bb(200);
Producer<bounded_buffer<MyData> > producer(&bb);
boost::thread produce(producer); // throws on this line
Here is the error that always appears when executing.
这是执行时总是出现的错误。
terminate called after throwing an instance of 'boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::lock_error> >'
what(): boost: mutex lock failed in pthread_mutex_lock: Invalid argument
The code for 'class bounded_buffer' is exactly as shown on this boost example page ... http://www.boost.org/doc/libs/1_55_0/libs/circular_buffer/example/circular_buffer_bound_example.cpp
'class bounded_buffer' 的代码与这个 boost 示例页面上显示的完全一样...... http://www.boost.org/doc/libs/1_55_0/libs/circular_buffer/example/circular_buffer_bound_example.cpp
I found this page here which seems to show the exact same thing, but I was unable to understand the answer given. Boost scoped_lock failed everytime
我在这里找到了这个页面,它似乎显示了完全相同的内容,但我无法理解给出的答案。Boost scoped_lock 每次都失败
Update:
Here is what Producer::operator() currently does when the functor is called. And my intentions for what I want this thread to do.
更新:
这是调用函子时 Producer::operator() 当前所做的事情。以及我想要这个线程做什么的意图。
void operator() () {
//init();
//read();
// this line just a test
m_container->push_front(value_type());
/*Eventually will do the following:
while (1) {
read_from_usb_device();
// then store data in global buffer (bb)
}*/
}
回答by StenSoft
The function returns and bb
gets destroyed but the thread is still running. And when m_container
tries to use the mutex, it (along with the whole m_container
) no longer exists.
函数返回bb
并被销毁,但线程仍在运行。当m_container
尝试使用互斥锁时,它(连同整个m_container
)不再存在。
You need to wait for the thread to end before you can destroy any data it uses:
您需要等待线程结束才能销毁它使用的任何数据:
boost::thread produce(producer);
produce.join();
Or you need to pass the ownership of the data to the thread, eg. using std::shared_ptr
(if you want to share the buffer with Consumer
as in the Boost example but unlike the example not joining the threads):
或者您需要将数据的所有权传递给线程,例如。使用std::shared_ptr
(如果您想与Consumer
Boost 示例中那样共享缓冲区,但与不加入线程的示例不同):
auto bb = std::make_shared<bounded_buffer<MyData> >(200);
Producer<bounded_buffer<MyData> > producer(bb);
Consumer<bounded_buffer<MyData> > consumer(bb);
boost::thread produce(producer);
boost::thread consume(consumer);