I’m constantly reading from a memory mapped file another process is writing to and use a mutex to synchronize this operation. In my few tests so far this works just fine, but… what if my application crashes right after acquiring the mutex and before releasing it? Is there any way to guarantee a release of the mutex, even in case of such a crash?
Also how would I handle a crash of the other process, which might not have released the mutex yet? Do I need to handle AbandonedMutexException each time I call mutex.WaitOne()?
Right now I’m doing it similar to this:
public MyState GetState()
{
MyState state = new State();
this._mutex.WaitOne();
try
{
state.X = this._mmView.ReadSingle(0);
state.Y = this._mmView.ReadSingle(4);
[..]
}
finally
{
this._mutex.ReleaseMutex();
}
return state;
}
_mmView is a MemoryMappedViewAccessor I instantiated before. This whole method GetState() gets called each frame as part of a game loop, so about every few milliseconds.
PS: Also, is there any other obvious problem why this could fail, that I didn’t already mention?
Eugen’s answer is correct — the operating system will release the mutex for you. Now think hard about what the consequences of this fact are:
In short, you are worrying about exactly the wrong thing. You shouldn’t be worried about what happens if my mutex never gets released. The worst thing that happens then is everyone waits forever, which is sad, but eventually the user will reboot the machine. You should be worried about what happens if mutex does get released because I crashed halfway through a mutation. In that scenario processes will now probably be crashing all over the place and the user’s data will be permanently corrupted.
Don’t get into that situation in the first place. The solution to the problem is do not crash when you have taken out a mutex for writing. If you don’t write programs that crash then you don’t have to worry about it, because its not going to happen. So just don’t write programs that ever crash.