我开始使用boost ::线程最近(操作系统,VS10,BoostPro),并发现互斥体可以通过任何线程解锁,而不是只有拥有它的线程。 此外它煤层,基本lock_guard +互斥组合做多锁内部的一些统计()和unlock(),但它不是一个大问题,我猜。
是否有人知道为什么会以这样的方式设计的? 是不是故意的? (或者有什么毛病我的编译环境/库?)
示例应用:
#include <iostream>
#include <boost/thread.hpp>
using namespace std;
class NamedThread
{
public:
NamedThread(string name_, boost::mutex& mtx_) :
mtx(mtx_), name(name_) {}
void operator ()()
{
for (int i = 0; i < 10; ++i)
{
boost::this_thread::sleep(boost::posix_time::milliseconds(1000));
cout << name << endl;
//boost::lock_guard<boost::mutex> guard1(mtx);
//boost::lock_guard<boost::mutex> guard2(mtx);
boost::unique_lock<boost::mutex> guard1(mtx);
boost::unique_lock<boost::mutex> guard2(mtx);
}
}
string name;
boost::mutex& mtx;
};
class UnlockerThread
{
public:
UnlockerThread(string name_, boost::mutex& mtx_) :
mtx(mtx_), name(name_) {}
void operator ()()
{
for (int i = 0; i < 100; ++i)
{
boost::this_thread::sleep(boost::posix_time::milliseconds(3000));
cout << name << ": unlocking" << endl;
mtx.unlock(); // !!! IT WORKS !!!
}
}
string name;
boost::mutex& mtx;
};
int main()
{
boost::mutex mtx;
NamedThread th2("Thread1", mtx);
boost::thread t2(th2);
UnlockerThread th3("UnlockerThread", mtx);
boost::thread t3(th3);
t2.join();
char ch;
cin >> ch;
return 0;
}
谢谢,