且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我如何获得废弃的 boost::interprocess::interprocess_mutex 的所有权?

更新时间:2023-11-13 22:37:16

遗憾的是,boost::interprocess API 不支持原样.但是,您可以通过以下几种方法来实现它:

Unfortunately, this isn't supported by the boost::interprocess API as-is. There are a few ways you could implement it however:

如果您在支持 pthread_mutexattr_setrobust_np 的 POSIX 平台上,请编辑 boost/interprocess/sync/posix/thread_helpers.hpp 和 boost/interprocess/sync/posix/interprocess_mutex.hpp 以使用强大的互斥锁,并以某种方式处理 EOWNERDEAD从 pthread_mutex_lock 返回.

If you are on a POSIX platform with support for pthread_mutexattr_setrobust_np, edit boost/interprocess/sync/posix/thread_helpers.hpp and boost/interprocess/sync/posix/interprocess_mutex.hpp to use robust mutexes, and to handle somehow the EOWNERDEAD return from pthread_mutex_lock.

如果您在其他平台上,您可以编辑 boost/interprocess/sync/emulation/interprocess_mutex.hpp 以使用生成计数器,锁定标志位于较低位.然后你可以创建一个回收协议,它会在锁定字中设置一个标志来指示一个挂起的回收,然后在超时后进行比较和交换以检查相同的代仍然在锁定字中,如果是,则替换它具有锁定的下一代价值.

If you are on some other platform, you could edit boost/interprocess/sync/emulation/interprocess_mutex.hpp to use a generation counter, with the locked flag in the lower bit. Then you can create a reclaim protocol that will set a flag in the lock word to indicate a pending reclaim, then do a compare-and-swap after a timeout to check that the same generation is still in the lock word, and if so replace it with a locked next-generation value.

如果您使用的是 Windows,另一个不错的选择是使用本机互斥对象;无论如何,他们很可能比忙着等待更有效率.

If you're on windows, another good option would be to use native mutex objects; they'll likely be more efficient than busy-waiting anyway.

您可能还想重新考虑使用共享内存协议 - 为什么不改用网络协议?

You may also want to reconsider the use of a shared-memory protocol - why not use a network protocol instead?