Eight, synchronization of threads
Although multithreading can bring us benefits, there are a number of problems to be solved. For example, for an exclusive system resource like a disk drive, because the thread can execute any code snippets of the process, and the thread is run automatically by system scheduling, with certain uncertainties, it is possible for two threads to operate on the disk drive at the same time, resulting in an operation error; For the computer in the banking system, it may be possible to use one thread to update its user database, and another thread to read the database in response to the needs of depositors, it is very likely that the thread reading the database reads the database that is not fully updated because only a portion of the data may have been updated at the time of reading.
It is called synchronization of threads to make the threads that belong to the same process work together in a coordinated manner. MFC provides a variety of synchronization objects, and we'll just describe four of the most commonly used:
Critical section (CCriticalSection)
Event (CEvent)
Mutex Amount (CMutex)
Signal Volume (CSemaphore)
With these classes, we can compare threads to sync easily.
A, the use of CCriticalSection class
When multiple threads access an exclusive shared resource, you can use the critical section object. Only one thread can have a critical section object at any one time, a thread with a critical section can access a protected resource or code snippet, and other threads that want to enter the critical section will be suspended until the thread that owns the critical section discards the critical section, guaranteeing that multiple threads will not be accessing the shared resource at the same time.
The use of the CCriticalSection class is simple, as follows:
Defines a global object for the CCriticalSection class (so that each thread can access it), such as CCriticalSection critical_section;
Before accessing the resource or code that needs to be protected, call Member Lock () of the CCriticalSection class to obtain the critical section object: critical_section.Lock(); call the function in a thread to obtain the critical section that it requests. If no other thread occupies the critical section object at this point, the thread calling lock () obtains the critical section, otherwise the thread is suspended and placed in a system queue until the thread that currently owns the critical section releases the critical section.
After accessing the critical section, use the CCriticalSection member function unlock () to release the critical section: critical_section.Unlock(); in layman's terms, thread a executes to critical_section. Lock (); If the other thread (B) is executing critical_section. Lock (); After the statement and critical_section. Unlock (); When the statement is before the statement, thread a waits until thread B finishes executing critical_section. Unlock (); statement, thread A will not continue execution.