Difference of critical region, mutual exclusion, semaphore, event __ Critical Zone

Source: Internet
Author: User
Tags function prototype mutex semaphore

The first original article: http://hi.baidu.com/cnrjm/blog/item/5d217e54ff863550564e00b9.html

Four kinds of control methods for synchronous mutual exclusion of process or thread
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.
3, signal Volume: To control a limited number of user resources and design.
4. Events: Used to inform the thread that some events have occurred, starting the successor task.

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.
MFC provides a number of full-featured classes, I used MFC implementation of the critical section. MFC provides a CCriticalSection class for critical areas, and it is easy to use this class for thread synchronization. Only the CCriticalSection class member function lock () and unlock () are used to calibrate the protected code fragment in the thread function. The resources used by the code after Lock () are automatically considered to be protected within the critical zone. These resources can be accessed by other threads after unlock.

Mutex (mutex)

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.

Several operations primitives contained in the mutex:
CreateMutex () Create a mutex
OpenMutex () Open a mutex
ReleaseMutex () Free Mutex
WaitForMultipleObjects () Wait for mutex object

Also MFC provides a CMutex class for mutexes. Using the CMutex class to implement mutex operations is very simple, but pay special attention to calls to CMutex constructors
CMutex (BOOL binitiallyown = FALSE, LPCTSTR lpszname = null, lpsecurity_attributes Lpsaattribute = null)
Do not use the parameters can not be filled out, random fill will appear some unexpected results of the operation.

signal Volume (semaphores)

Semaphore objects are synchronized to threads in a way that allows multiple threads to use shared resources at the same time as the PV operation in the operating system, unlike the previous methods. It indicates the maximum number of threads accessing the shared resource at the same time. It allows multiple threads to access the same resource at the same time, but needs to limit the maximum number of threads that access the resource at the same time. When you create a semaphore with CreateSemaphore (), you indicate both the maximum allowable resource count and the current count of available resources. Typically, the current available resource count is set to the maximum resource count, with each additional thread accessing the shared resource, the current available resource count is reduced by 1, and semaphore signals can be emitted as long as the current available resource count is greater than 0. However, when the current available count is reduced to 0 o'clock, the number of threads currently consuming resources has reached the maximum allowable number and cannot allow other threads to enter, at which point the semaphore signal will not be emitted. After the thread finishes processing the shared resource, it should pass the ReleaseSemaphore () function to add the current available resource count to 1 while leaving. The current count of available resources is never likely to be greater than the maximum resource count at any time.
The concept of PV operation and semaphore is proposed by E.w.dijkstra, a Dutch scientist. Semaphore S is an integer, s greater than equals zero represents the number of resource entities available to the concurrent process, but s less than zero indicates the number of processes waiting to use the shared resource.
P Operation Request Resources:
(1) s minus 1;
(2) If s minus 1 is still greater than or equal to zero, then the process continues to execute;
(3) If s minus 1 is less than 0, the process is blocked into a queue corresponding to the signal and then transferred to the process schedule.
V Operation Frees Resources:
(1) s plus 1;
(2) If the addition result is greater than 0, the process continues to execute;
(3) If the addition result is less than or equal to zero, then a waiting process is awakened from the waiting queue of the signal, which is then returned to the original process for execution or transfer to the process schedule.

Several operational primitives contained in the semaphore:
CreateSemaphore () Create a semaphore
OpenSemaphore () opens a semaphore
ReleaseSemaphore () releasing semaphore
WaitForSingleObject () waiting signal volume


Event object can also maintain synchronization of threads by notifying actions. And you can implement thread synchronization operations in different processes.
Semaphore contains several operational primitives:
   CreateEvent () Create an event
   openevent () Open an event
   Set Event () callback event
   WaitForSingleObject () waits for an event
   waitformultipleobjects () Waiting for multiple events
   waitformultipleobjects function prototype:
   waitformultipleobjects (
   I N DWORD ncount,//wait handle number
   in CONST HANDLE *lphandles,//point to handle array
   in BOOL Bwaita ll,//is fully waiting for the flag
   in DWORD dwmilliseconds//wait Time
parameter ncount Specifies the number of kernel objects to wait on. The array that holds these kernel objects is pointed to by Lphandles. fWaitAll specifies two ways of waiting for the specified Ncount kernel object, which returns when all objects are notified, and false if any one of them is notified. The role of dwmilliseconds here is exactly the same as the role in WaitForSingleObject (). If the wait times out, the function returns to Wait_timeout.

1. A mutex is very similar to a critical section, but a mutex can be named, meaning it can be used across processes. So creating a mutex requires more resources, so using a critical section for just the inside of a process can lead to a speed advantage and reduce the amount of resources taken up. Because a mutex is a mutex that spans a process, once created, it can be opened by name.
2. Mutexes (mutexes), semaphores (semaphore), events (event) can be used across processes to synchronize data operations, while other objects are independent of data synchronization operations, but for processes and threads, if processes and threads are not signaled in the running state, After exiting for signaled status. So you can use WaitForSingleObject to wait for processes and threads to exit.
3. A mutex can be used to specify the way in which a resource is exclusive. However, if there is one of the following conditions can not be processed through the mutex, for example, now a user purchased a three concurrent access to the database system, can be based on the number of access licenses purchased by the user to determine how many threads/processes can be database operations at the same time, At this time, if the use of mutual exclusion is no way to complete this requirement, the semaphore object can be said to be a resource counter.

For a more detailed introduction, please see here: http://www.cppblog.com/killsound/archive/2009/07/15/16147.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.