scope(exit)
Sean Kelly
sean at f4.ca
Fri May 12 17:41:51 PDT 2006
MM wrote:
> I've been reading through Exception Safe Programming page and I had a question:
>
> why not:
> scope(exit) unlock(m);
> lock(m);
>
> iso the inverse?
> lock() might crash but might still have locked m
> Or is this stpd reasoning?
> unlocking m when it is not locked should not ba a problem or the scope(exit)
> could check whether or not m is locked?
Personally, I find the basic guarantee to be of very limited use. For
most operations, the weak guarantee seems far more appropriate, and I
believe it is reasonable to expect that of the lock function. In other
words, if the lock function fails then I would expect m to be in the
state it was in prior to the lock call. Further, it's possible that
unlock might consider being asked to unlock a mutex that the calling
thread doesn't own to be an error condition, which may result in an
exception being generated. Therefore, if lock fails and throws and
exception and scope(exit) unlock(m) therefore fails and throws an
exception as well, the application will terminate because it has two
exceptions in flight simultaneously. Therefore:
lock(m);
scope(exit) unlock(m);
is preferred because unlock will only be called if a lock was
successfully obtained, and will be called regardless of whether the
following code generates an error or completes successfully.
Sean
More information about the Digitalmars-d
mailing list