exception handling - Automatic locking/unlocking using scope in C++ (from C# background) -


I have been using C # for the past few years and I am currently doing a bug fix in C ++. In C #, I can use lock on an object to protect my code thread:

  lockObject {// do some work}  

If there was an exception within a code

then unlock, unlock is something similar in C ++? At the moment I can either think:

  // code {auto lock lock}; // do some work} // more code  

but I do not like curly braces for the scope of my AutoLock. I'm currently doing:

  AutoLock lock (lock object); // Lock some functions. Unlock (); One exception to  

and // some work is to quit leaving an exception to unlock.

What I am doing is the moment's work, but I am thinking that better way, thanks.

But for the scope of my AutoLock , curly braces do not like it.

This has been done in C ++.

Note that you do not need a separate area block for each AutoLock ; The following is also OK:

  {AutoLock lock1; Auto Lock Lock 2; // more code goes here) // lock2 is destroyed, lock 1 is destroyed  

This is not a separate circular block; If you are locking something in the function and it does not need to unlock the function till the return, you can use only the function scope to limit the lock. Similarly, if you have a frequency in each loop block While you are locking something, you can use the scope block of the loop to block the lock.

When you complete it, your approach to manually unlocking the Mute X is fine, but it is not idiomatic C ++ and it is not clear. It's hard to figure out where the Mute X is unlocked (not very hard, but hard work is required).


Comments