基本上,我不明白为什么这个代码会运行。我相信锁定互斥锁会导致其他尝试锁定互斥锁阻塞,但情况似乎并非如此。
#include <cstdio>
#include <boost/thread.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
class Foo
{
public:
Foo()
{
pThread = boost::make_shared< boost::thread >( [=](){
boost::unique_lock< boost::mutex >( mtx );
while( true )
{
fprintf( stdout, "I have the mutex\n");
}
} );
}
void bar()
{
boost::unique_lock< boost::mutex >( mtx );
fprintf( stdout, "bar got the mutex\n");
}
private:
boost::mutex mtx;
boost::shared_ptr< boost::thread > pThread;
};
int main()
{
Foo foo;
while( true )
{
foo.bar();
}
}
编辑: 添加一些睡眠后输出,以便输出可管理。
bar got the mutex
I have the mutex
bar got the mutex
I have the mutex
bar got the mutex
I have the mutex
bar got the mutex
I have the mutex
bar got the mutex
I have the mutex
bar got the mutex
I have the mutex
bar got the mutex
I have the mutex
bar got the mutex
I have the mutex
bar got the mutex
I have the mutex
bar got the mutex
I have the mutex
^C
这与我之前报道的不同,这是更新后的代码。我不确定睡眠线程会如何影响输出。
#include <cstdio>
#include <boost/thread.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
class Foo
{
public:
Foo()
{
pThread = boost::make_shared< boost::thread >( [=](){
boost::unique_lock< boost::mutex >( mtx );
while( true )
{
boost::this_thread::sleep( boost::posix_time::milliseconds( 1000 ) );
fprintf( stdout, "I have the mutex\n");
}
} );
}
void bar()
{
boost::unique_lock< boost::mutex >( mtx );
fprintf( stdout, "bar got the mutex\n");
}
private:
boost::mutex mtx;
boost::shared_ptr< boost::thread > pThread;
};
int main()
{
Foo foo;
while( true )
{
boost::this_thread::sleep( boost::posix_time::milliseconds( 1000 ) );
foo.bar();
}
}
答案 0 :(得分:4)
你甚至没有锁定互斥锁。
boost::unique_lock< boost::mutex >( mtx );
它被解析为变量mtx
的声明,其类型为boost::unique_lock< boost::mutex >
,使用默认构造函数初始化。相反,您需要使用引用可锁定对象的构造函数:
boost::unique_lock< boost::mutex > lock{mtx};