1. The critical section can only be used for mutually exclusive access between threads in the same process as the object, and the mutex may be used for mutually exclusive access between object processes and threads.
2, the critical section is not the kernel object, only in the user state to lock operation, fast; the mutex is the kernel object, the lock operation in the nuclear mentality, the speed is slow.
3. The critical section and the mutex are available under Windows platform, and only the mutex is available under Linux.
1, critical area: Through the serialization of multithreading to access public resources or a section of code, fast, suitable for controlling data access.
2. Mutual exclusion: Designed to coordinate a separate visit to a shared resource.
Critical area (Critical section)
An easy way to ensure that only one thread can access the data at a certain point in time. Only one thread is allowed to access the shared resource at any time. If more than one thread attempts to access the critical section at the same time, all other threads that attempt to access this critical area will be suspended after one thread enters, and the thread that continues into the critical section leaves. After the critical section is freed, other threads can continue to preempt and thus achieve the purpose of operating the shared resource in an atomic manner.
The critical section contains two operational primitives:
EnterCriticalSection () Enter critical section
LeaveCriticalSection () out of critical zone
After the EnterCriticalSection () statement executes, the code will enter the critical section, and no matter what happens, you must ensure that the matching leavecriticalsection () can be executed. Otherwise, the shared resources protected by the critical section will never be freed. Although critical areas are synchronized quickly, they can only be used to synchronize threads within this process, not to synchronize threads in multiple processes.
The mutex is very similar to the critical section, and only the line that owns the mutex Cheng has access to the resource, and because the mutex has only one, it determines that the shared resource will not be accessed by multiple threads at the same time. The thread that currently occupies the resource should hand over the mutex that it owns after the task has been processed so that other threads can access the resource after it is acquired. The mutex is more complex than the critical region. Because mutual exclusion not only enables the secure sharing of resources within different threads of the same application, but also enables secure sharing of resources between threads of different applications.