gpt4 book ai didi

multithreading - Boost:可能从任何线程解锁互斥锁吗?

转载 作者:行者123 更新时间:2023-12-03 13:16:17 27 4
gpt4 key购买 nike

我最近开始使用boost::thread(WinXP,VS10,BoostPro),发现互斥锁可以由任何线程解锁,而不能仅由拥有它的线程解锁。
另外,它似乎表明基本的lock_guard + Mutex组合正在对多个lock()和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;
}

谢谢,

最佳答案

boost文档非常清楚,调用mutex.unlock的前提是“当前线程拥有* this”。这并不意味着违反该先决条件将导致异常/错误/崩溃(尽管对于调试版本而言可能会很好),但是在这种情况下,您不能依赖任何特定的行为。

Win32实现似乎使用原子指令实现了互斥锁的大多数逻辑-大概是由于对Win32上更复杂的互斥锁类型(递归/定时)的有限支持。 Win32的 native 关键部分只能用于简单的互斥体(而Win32的 native 互斥体对于进程内的互斥体而言过于繁重)。

关于multithreading - Boost:可能从任何线程解锁互斥锁吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7371766/

27 4 0