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

标签 multithreading boost mutex

我最近开始使用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/

相关文章:

multithreading - Akka:如何确保已收到消息?

boost - BGL edge(u,v,g),带有用于边缘列表的自定义关联容器

c++ - 你能帮我将互斥对象应用到这段代码吗?

c# - 我需要线程锁对象吗?

java - 使用套接字在 JAVA 中同时将客户端连接到多个服务器

c++ - C++中boost vector 的子类

c++ - 使用 Boost 无法解析的外部符号

go - 我可以在Go中使用特定值锁定吗?

c - 从当前线程中找出事件线程的状态。 (稳健互斥体的实现)

java - 尝试在可运行对象中同步方法