Ender
Ender

Reputation: 1778

What does mutex lock fail with invalid argument mean?

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

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

Update:
Here is what Producer::operator() currently does when the functor is called. And my intentions for what I want this thread to do.

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)
    }*/
}

Upvotes: 14

Views: 53081

Answers (1)

StenSoft
StenSoft

Reputation: 9609

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.

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

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

Upvotes: 11

Related Questions