A pair of glasses.
1) What you want to find is a “one-time template”. Be very careful to implement it correctly. Of course, Mutex already implements a one-time template, so it’s not clear why you want to make your own, but it's good to know it.
Look at this question for some additional thoughts on the feasibility of using a one-time template, as if it were RAII:
Is it insulting to use IDisposable and "using" as a means to get "scope behavior". for exception safety?
2) Try-finally also has the semantics you want. Of course, the “used” block is just syntactic sugar for try-finally.
3) Are you sure you want to let go of the mutex when it throws something? Are you sure you want to drop into a protected region?
This is a bad code smell for the following reason.
Why do you have a mutex in the first place? Usually, since the pattern is as follows:
- condition agreed but outdated
- block access to state
- make a condition mismatch
- make state consistent
- share status
- now consistent and new
Think about what happens when you throw an exception before you make the state consistent. You open access to a state that is now incompatible and outdated .
It might be better to keep the castle. Yes, this means a risk of deadlocks, but at least your program does not work on garbage, an outdated, inconsistent state.
This is a terrible, terrible thing that throws an exception from within a blocking region, and you should avoid this whenever possible. The exception thrown inside the lock forces you to choose between two terrible things: either you get deadlocks, or you get crazy crashes and irreproducible behavior when your program manages an inconsistent state.
The pattern you really have to follow:
- condition agreed but outdated
- block access to state
- make a condition mismatch
- make state consistent
- if an exception occurs, rollback to an obsolete, consistent state
- share status
- now agreed and, if there were no exceptions, fresh
This is a much safer alternative, but writing code that does such transactions is tough. No one said multithreading was easy.