gpt4 book ai didi

c++ - boost::interprocess::named_mutex 与 CreateMutex

转载 作者:可可西里 更新时间:2023-11-01 13:29:15 28 4
gpt4 key购买 nike

我想从 CreatMutex 切换到 boost::interprocess::named_mutex 以将我的应用程序限制为单个实例。当应用程序正常运行和结束时,这两种方法都有效。但是,当应用程序崩溃并使用 boost::interprocess::named_mutex 时,锁不会被释放。我可以通过使用两个 name_mutex 来解决这个问题,但我真的不明白这个问题。

为什么 boost::interprocess::named_mutex 的锁在应用程序崩溃时没有释放,但它是通过 CreatMutex 释放的?有什么区别?


boost::interprocess::named_mutex mutex(boost::interprocess::open_or_create, "my_mutex");
boost::interprocess::scoped_lock<boost::interprocess::named_mutex> lock(mutex, boost::interprocess::try_to_lock);
if(!lock) {
return 1; //exit
}
//application may crash here.
boost::interprocess::named_mutex::remove("my_mutex");
return 1; //exit

最佳答案

警告:我没有花太多时间在 boost::interprocess 上,所以这些信息只是来自对源代码的快速检查。也就是说,我经常使用 Windows 同步 API,所以这里...


这两种进程间同步方法的主要区别在于对象在系统中的存在方式。

有了 boost::interprocess::named_mutex 以及系统特定的互斥锁,同步对象看起来就像是作为系统文件创建的。该文件的位置基于注册表条目(见注释 1)(至少在 Boost 1.54.0 中是这样)...它很可能位于 Common Application Data 文件夹下(见注释 2)。当应用程序崩溃时,在您的情况下,该文件不会被删除。我不确定这是否是设计使然...但是在应用程序崩溃的情况下,最好不要弄乱文件系统,以防万一

相反,当您使用 CreateMutex 时,会在内核模式下创建一个对象,对于命名的互斥锁,多个应用程序可以访问该对象。您可以通过在创建互斥体时指定名称来获得该互斥体的句柄,而当您对其调用 CloseHandle 时,您将失去该句柄。当没有更多句柄引用它时,互斥对象将被销毁。

其中的重要部分在 documentation 中:

The system closes the handle automatically when the process terminates. The mutex object is destroyed when its last handle has been closed.

这基本上意味着 Windows 将在您的应用程序之后进行清理。

请注意,如果您不执行 ReleaseMutex,并且您的应用程序在它终止时拥有该互斥锁,那么等待线程或进程可能/很可能会看到该互斥锁已被放弃(WaitForSingleObject 返回 WAIT_ABANDONED),并会获得所有权。

对于没有提供解决方案,我深表歉意,但我希望它能回答您关于为什么这两个系统的行为不同的问题。


  1. 顺便说一句,使用注册表项获取此信息很糟糕 - 使用 SHGetKnownFolderPath 会更安全,也更不会过时。但我离题了。

  2. 根据您的操作系统版本,这可能是 %ALLUSERSPROFILE%\Application Data\boost.interprocessProgramData\boost.interprocess,或者完全是其他地方.

关于c++ - boost::interprocess::named_mutex 与 CreateMutex,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20379817/

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