开发者

Named process internal mutexes with C/C++?

Are there ways to implement named process internal mutexes using C/C++ (in Unix/开发者_Go百科Linux)?

The trick is that the mutexes lifetime would need to be process persistent. Unlike for example the named posix semaphores and shared memory.

You could have for example pthread mutexes, in a dynamic map and access them with some id. But then you need to protect the mutexes somehow.

If you use memory mapped files or shared memory, you get the filesystem persistence...

Any ideas?


You can always revert back to the older (albeit depreciated) System V semaphores which work off a common key-value rather than a POSIX named semaphore which has file-system persistence. That being said, a POSIX named semaphore will not have file-system persistence if you close and then unlink the semaphore in every process using it. Once the last process that was using the semaphore has exited, the semaphore reference will be removed from the file-system. If you're worried about the visibility of the semaphore at the file-system level, you can always precede the name of the semaphore with a "." in order to make the file invisible, and/or adjust the permissions on the file so that only the current user or some privileged user/group can access the semaphore.


What do you mean by "process-persistent"? If you want them to persist after the process ends, just use named semaphores or named shared memory, and prefix the name with something unique to your program. If you want them to go out of existence when the process terminates, just use any kind of hash map protected by an rwlock (locked in read mode to lookup existing names, write mode to add/remove names).


It's quite simple. Have a mapping of strings to mutexes, and a mutex to protect this mapping:

std::map<std::string, pthread_mutex_t *> mutexMap;
pthread_mutex_t mutexMap_lock = PTHREAD_MUTEX_INITIALIZER;

When you need to find a mutex, take the mutexMap_lock lock first. Once you have the mutex, drop the lock, and cache the mutex pointer so you don't have to keep referring to this mutexMap point of contention.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜