问题
I have a resource which I need to protect access to within a process, and across multiple processes. I've managed this by creating a named mutex via boost::interprocess:named_recursive_mutex
, and it works great.
#include <boost/interprocess/sync/named_recursive_mutex.hpp>
boost::interprocess::named_recursive_mutex mut(
boost::interprocess::open_or_create, "MY_SHARED_MUTEX_123");
However, it's to my understanding that this should be cleaned up eventually via remove()
, ie:
mut.remove("MY_SHARED_MUTEX");
However, this call appears to completely clobber the mutex, rather than check/decrement a reference count, so I'm trying to find a safe way to issue the remove()
call when I know that no other processes are using it. I could create a chunk of shared memory via boost as well, but that does not appear to have a shared reference count either.
I've found a similar question on SO, but the accepted answer doesn't seem adequate for my needs, as it just refers to the "boost docs", but doesn't give a clear indicator as to when remove()
can be safely issued.
How can I safely clean up this named mutex when I'm certain the last process accessing it has closed, or possibly crashed?
Thank you.
回答1:
There isn't any reference counting supported to my knowledge.
If you are starting or stopping your processes using for example shell script you could remove the shared memory files at start/stop from the script.
If you have one process that is always starting first then you could use it to remove shared memory files at program start (or similarly in last stopping process at program stop).
Another approach would be implementing reference counting yourself using shared memory - last process would delete all shared memory files. However this won't work if one of the processes crash, you could still try removing in segfault signal handler but this may not always work too.
Update: As @sehe mentioned boost::interprocess::shared_ptr
can be used for reference counting.
来源:https://stackoverflow.com/questions/31707347/boostnamed-mutex-safely-cleaning-up-when-last-process-closes