boost::interprocess 新版本修复了死锁

  • Boost 是一个开源 C++ 算法库,是官方认证的对标准 C++ 的扩充(有点类似 python 的 anaconda)。C++ 15 / 17 等新版本有很多特性也会参考 boost 库;
  • boost:Interprocess 实现了进程间通信功能,包括共享内存、内存映射文件、信号量、文件锁、消息队列等;
  • 共享内存 指可被多个进程存取的内存,被用作进程间的通信。

boost::interprocess 在 1.78 版本之前如果进程崩溃可能导致死锁。从18年就有人提出这个issue,21年才修复。
最简单的复现方法是执行三遍下面的代码:

1
2
3
4
5
6
7
8
#include "boost/interprocess/managed_shared_memory.hpp"

int main() {
boost::interprocess::managed_shared_memory managed_shm{
boost::interprocess::open_or_create, "Boost", 1024
};
int* i = managed_shm.construct<int>("Int")(99);
}
  • 第一遍在共享内存中创建 Boost 文件,并写入一个 Key 为 Int 的变量 99;
  • 第二遍尝试再次写入时发现已经有这个Key了,写不进去。程序崩溃,并抛出异常:
    terminate called after throwing an instance of 'boost::interprocess::interprocess_exception'
    what(): boost::interprocess_exception::library_error
  • 第三遍因为上次的崩溃时没有释放锁,程序死锁;
  • 新版本的 boost 在第三次执行程序的时候会不会死锁,抛出异常 :
    terminate called after throwing an instance of 'boost::interprocess::lock_exception'
    what(): boost::interprocess::lock_exception

原因在这几行,如果不想更新boost,改那几行也可以。

如果编译器支持 _POSIX_C_SOURCE >= 200809L,在构造锁的时候判断 pthread_mutexattr_setrobust(&m_attr, PTHREAD_MUTEX_ROBUST) != 0

pthread_mutexattr_setrobust 的说明在这里