Linux inter-process reentrant semaphore

拟墨画扇 提交于 2019-12-08 05:40:24

问题


I'm porting a Windows application to Linux and I have a synchronization problem.

In Windows I'm using a system-level named mutex to sync access to a shared memory block.

How do I emulate that in Linux? I've created a SystemV semaphore, using semget. The problem is that it is not reentrant, if I already hold it it will block, unlike on Windows. I could add a reference count to it, but then I would need to synchronize access to that, which means another (this time for the current process only) mutex.

Is there a class somewhere which provides a reentrant interprocess lock (maybe in Boost)?

BTW, using a file lock is not acceptable since it will probably be too slow (I need ultra-low latency communication between the two processes).


回答1:


You can just use a shared (interprocess), recursive pthread_mutex_t. Create a normal pthread_mutex (stored in shared memory) and set its attributes using pthread_mutexattr_settype with the PTHREAD_MUTEX_RECURSIVE flag, and then call pthread_mutexattr_setpshared with the PTHREAD_MUTEX_SHARED flag.

That will give you a reentrant, interprocess lock.




回答2:


You could try building your own out of futexes. See usersem.c in this tarball.



来源:https://stackoverflow.com/questions/1748902/linux-inter-process-reentrant-semaphore

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!