gpt4 book ai didi

c++ - 与 boost::interprocess_mutex 相比,为什么不在共享内存中使用 boost::mutex?

转载 作者:搜寻专家 更新时间:2023-10-31 01:53:32 25 4
gpt4 key购买 nike

在愤怒中学习和使用增强共享内存一段时间后,我得出了一个心智模型,即何时使用哪种类型的互斥体,看起来像这样:

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,我猜对了吗?有人可以给出它不起作用的技术幕后原因,或者至少在什么情况下它不起作用?

最佳答案

关于第 3 点:您的 boost::mutex 对您的其他进程不可见。进程间互斥使用系统全局命名的对象,可以被另一个进程访问,据我所知,boost::mutex 没有。

你的 boost::mutex 在共享内存中创建,例如在 Windows 中,有一个 HANDLE 到一个 windows Mutex 对象,它将分配在你的进程的私有(private)堆。该堆对其他进程不可见。

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

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

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

关于c++ - 与 boost::interprocess_mutex 相比,为什么不在共享内存中使用 boost::mutex?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11051834/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com