C ++ object mutual vision

zhaozj2021-02-16  57

The mutual exclusive access, C # has a lock keyword, Java has a synchronized keyword, and C under Windows is only programmed by the CriticalSection API. Here chicks shooter Mutex classes: class Mutex {public: Mutex () {InitializeCriticalSection (& m_cs);} virtual ~ Mutex () {DeleteCriticalSection (& m_cs);} void Lock () {EnterCriticalSection (& m_cs);} void UnLock ( ) {LeaveCriticalSection (& M_CS);} private: critical_section m_cs;}

Mutex's Lock and Unlock are generally used, in order to avoid deadlocks, the critical area must immediately update. In order to ensure UNLOCK, you can unlock in Try ... catch ... finally's finally, there is another method to define the MutexGuard class: Class Mutexgurad {public: Explicit MutexGuard (Mutex & Mutex): m_mutex (mutex) {mutex. Lock ();} Virtual ~ mutexgurad () {mutex.unlock ();} private: mutex & m_mutex;}; MutexGuard is also very simple, assuming that the member variable MUTEX M_MUTEX is defined within the critical area code: Used in the critical area: {MUTEXGURAD Guard (M_Mutex); // Cross-border Processing Code} Local Variable Guard does not seem to be used at all, in fact, using its lifetime: Creating a Guard, Lock, unlock when you release Guard. Note {}, which defines the timing of UNLOCK. Like the try ... finally, even if the processing code has exception, UNLOCK ensures that it can be executed. Small chickens are quite like to use MutexGuard methods because it is very convenient; users don't even have to know Mutex is LOCK / UNLOCK, or Enter / Leave.

转载请注明原文地址:https://www.9cbs.com/read-18189.html

New Post(0)