"Turn from" here
Writing programs is not easy, and writing multithreaded programs is not easy. Believe that the program that writes too many threads should have such a painful process, what kind of situation? Friends should look at the code and understand,
void data_process () {entercriticalsection ( ); if (/* Error happens */ ) {Leavecriticalsectio N (); return ; if (/* Other error happens */ ) { return ; } leavecriticalsection ();}
The above code illustrates a situation. This multi-threaded mutex is often encountered during code writing. Therefore, every time you operate on shared data, you need to do entercriticalsection and leavecriticalsection the data. However, it is not smooth sailing in the middle. There is a good chance that you will meet all kinds of mistakes. Then your program needs to jump out of the way. You may remember to exit the critical section at the beginning of the error. However, if there are more errors, you may not remember the operation. This is the end of the mistake, and other threads have no chance of acquiring the lock.
So, is it possible to use the features of C + + to automatically handle this situation? It really is. Let's take a look at the code below.
classclock{critical_section&CS; Public: CLock (critical_section&Lock): CS (Lock) {entercriticalsection (&CS); } ~CLock () {leavecriticalsection (&CS); }}classprocess{critical_section cs; /*Other data*/ Public: Process () {initializecriticalsection (&msg; } ~process () {deletecriticalsection (&CS);} voiddata_process () {CLockLock(CS); if(/*Error Happens*/){ return; } return; }}
An important feature of C + + is that the system automatically calls the class's destructor whenever the function exits. In the data_process function of the process class, the function creates a clock class at the beginning. Then, in the creation of this class, in fact, the beginning of the critical section of the PK. So once into the critical section, in the error can not be in time to exit the critical area? At this point, the advantages of the C + + destructor appear. Because no matter when the error occurs, before the function exits, the system will help us with the aftermath. What's the aftermath? Is that the system calls the clock's destructor, which exits the critical section. In this way, our aim is achieved.
In fact, this is a C + + trick.
C + + multithreading--locking techniques