boost :: scoped_lock似乎没有锁定std :: cout

时间:2016-03-21 17:13:05

标签: c++ multithreading boost mutex boost-mutex

我正在使用boost 1.54.0和Visual Studio 2010.对于代码:

#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;
}

大约一半时间我得到以下内容(显然有不同的线程ID和执行顺序):

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

......而不是这个(这是我所期待的):

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

然而,使用

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

......似乎没有任何问题。

输出似乎总是遵循相同的模式。我是否错误地使用了互斥锁,还是与std :: cout有关?

1 个答案:

答案 0 :(得分:6)

替换

    boost::mutex::scoped_lock(mx1);

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

你成了最常发生错字的受害者: - )