ben
ben

Reputation: 59

How to release boost::interprocess::named_mutex when the process crashes

I used boost::interprocess to create a boost::multi_index data structure in shared memory. There are many client processes that will access this data structure. When accessing, I will lock the data structure. The problem I encountered is Once the client process is accessing the data structure and crashes without releasing the occupied lock, then all other client processes cannot access the data structure. I use boost::interprocess::named_mutex, I Know that boost::interprocess::file_lock can be automatically released when the process crashes, but because he has a lot of restrictions, so I have no use, I don't know if there is any good way to solve this problem, thank you!

Upvotes: 3

Views: 1971

Answers (2)

I guess you can try to access the mutex with timed_lock and, if you get a timeout, forcibly delete the mutex with remove.

Upvotes: 1

Remy Lebeau
Remy Lebeau

Reputation: 595971

Do not place a mutex in shared memory. The boost documentation for named_mutex says:

https://www.boost.org/doc/libs/1_70_0/doc/html/boost/interprocess/named_mutex.html

A mutex with a global name, so it can be found from different processes. This mutex can't be placed in shared memory, and each process should have it's own named_mutex.

The whole point of using a named mutex is that multiple processes can create their own local mutex objects using the same name and they will share an underlying mutex that they can sync on. If a given process locks the mutex and then crashes, the underlying shared mutex will be released automatically by the OS, allowing another process to lock it (depending on OS, the underlying mutex API may report that the mutex had been unlocked abnormally).

Upvotes: 3

Related Questions