Search code examples
c++multithreadingboostmutexboost-mutex

boost::scoped_lock appears not to lock std::cout


I'm using boost 1.54.0 and Visual Studio 2010. For the code:

#include <iostream>
#include "boost/thread/thread.hpp"
#include "boost/thread/mutex.hpp"

boost::mutex mx1;

void func1()
{
    {
        boost::mutex::scoped_lock(mx1);
        std::cout << "Thread " << boost::this_thread::get_id() << " starting work." << std::endl;
    }
    int x = 0;
    for (int i=0; i<100; i++)
        x++;
    {
        boost::mutex::scoped_lock(mx1);
        std::cout << "Thread " << boost::this_thread::get_id() << " finished." << std::endl;
    }
}

int main(void)
{
    boost::thread thread1(&func1);
    boost::thread thread2(&func1);
    thread1.join();
    thread2.join();
    return 0;
}

About half the time I get the following (with varying thread ids and execution order, obviously):

Thread Thread 15b0 starting work.
1a18 starting work.
Thread 15b0 finished.
Thread 1a18 finished.

...instead of this (which is what I'd expect):

Thread 15b0 starting work.
Thread 1a18 starting work.
Thread 15b0 finished.
Thread 1a18 finished.

However, using

mx1.lock();
std::cout << "Thread " << boost::this_thread::get_id() << " starting work." << std::endl;
mx1.unlock();

...seems to work with no problems.

The output always seems to follow the same pattern. Am I using the mutex incorrectly, or is it something to do with std::cout?


Solution

  • Replace

        boost::mutex::scoped_lock(mx1);
    

    with

        boost::mutex::scoped_lock lock(mx1);
    

    you fell a victim of the most frequently occurring typo with the scoped lock:-)