【问题标题】:Why not to use boost::mutex within shared memory compared to boost::interprocess_mutex?与 boost::interprocess_mutex 相比,为什么不在共享内存中使用 boost::mutex?
【发布时间】:2012-06-18 14:12:41
【问题描述】:

在愤怒中学习和使用提升共享内存一段时间后,我得出了一个心智模型,即何时使用哪种类型的互斥体,如下所示:

class IntendedToResideInProcessMemory {
    boost::mutex mutex_for_this_process; // 1
    boost::interprocess::interprocess_mutex
        ok_but_pointless_to_use_interprocess_mutex_here; // 2
}

class IntendedToBeCreatedInSharedMemory {
    boost::mutex bad_mutex_at_a_guess_this_will_allocate_something_on_heap;// 3
    boost::interprocess::interprocess_mutex
        good_for_multiprocess_shared_lock; // 4
}

我希望我原则上没有弄错,所以如果是这样,请纠正我。我的意图是推进和纠正现有代码以及我自己的不符合这张图片但我想确定的代码。

这个问题的两个部分: 我认为它确实没问题,但使用 //2 毫无意义 - 在上下文中这不如 //1 好,但原因是什么?性能?

对于 //3,我猜对了吗?有人可以给出它不起作用的技术幕后原因,或者至少在什么情况下它不起作用?

【问题讨论】:

    标签: c++ shared-memory boost-interprocess boost-mutex


    【解决方案1】:

    关于第 3 点:您的 boost::mutex 对您的其他进程不可见。进程间互斥体使用系统全局命名的对象,该对象可以被另一个进程访问,afaik,boost::mutex 不能。

    您在共享内存中创建的boost::mutex,例如在Windows 中,有一个HANDLE 指向一个Windows Mutex 对象,该对象将分配在您的进程的私有堆上。此堆对其他进程不可见。

    如果你查看boost::mutex 类,它有这个typedef

    typedef platform-specific-type native_handle_type; 特定于平台。

    另一个例子:POSIX互斥体是由它们的地址来标识的,这在进程之间是不同的 感谢@DeadMG 这个例子:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-15
      • 2011-07-22
      • 2011-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多