1

我正在使用 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 有关?

4

1 回答 1

6

代替

    boost::mutex::scoped_lock(mx1);

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

您成为使用范围锁最常见的错字的受害者:-)

于 2016-03-21T17:16:08.153 回答