"Go" "Linux" critical zone, mutex, Semaphore, event difference

Source: Internet
Author: User
Tags mutex semaphore

Original address: http://blog.itpub.net/10697500/viewspace-612045/

Four types of process or thread synchronization mutex control method in Linux
1, critical area: Through the serialization of multithreading to access public resources or a piece of code, fast, suitable for controlling data access.
2. Mutex: Designed to coordinate separate access to a shared resource together.
3. Semaphore: Designed to control a limited number of user resources.
4. Event: Used to notify the thread that some events have occurred, thus initiating the start of the successor task.

Critical area (Critical section)


An easy way to ensure that only one thread can access the data at a 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 section after one thread has entered will be suspended and continue until the thread entering the critical section leaves. When the critical section is released, other threads can continue to preempt, and in this way achieve the purpose of atomic manipulation of shared resources.
The critical section consists of two operation Primitives:
EnterCriticalSection () Enter the critical section
LeaveCriticalSection () Leave the critical section
After the EnterCriticalSection () statement executes, the code will enter the critical section, and no matter what happens, it must be ensured that the matching leavecriticalsection () can be executed. Otherwise, the shared resources protected by the critical section will never be freed. Although critical section synchronization is fast, it can only be used to synchronize threads within this process and not to synchronize threads in multiple processes.
MFC provides a lot of fully functional classes, I use MFC to implement the critical section. MFC provides a CCriticalSection class for critical sections, and it is very simple to use this class for thread synchronization. Just use the CCriticalSection class member function lock () and unlock () in the thread function to demarcate the protected code fragment. The resources used by the Lock () are automatically considered to be protected in the critical zone. These resources can be accessed by other threads after unlock.
Mutex (mutex)

The mutex is similar to the critical section, and only the line friend with the mutex has permission to access the resource, because there is only one mutex object, so it is determined that the shared resource will not be accessed by multiple threads at the same time in any case. The thread that currently occupies the resource should hand over the owning mutex 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 section. Because using mutexes not only enables the secure sharing of resources in different threads of the same application, but also enables secure sharing of resources between threads of different applications.

The mutex contains several operations primitives:
CreateMutex () creates a mutex
OpenMutex () Open a mutex
ReleaseMutex () Release mutex
WaitForMultipleObjects () waits for mutex object

Similarly, MFC provides a CMutex class for mutexes. Using the CMutex class to implement mutex operations is straightforward, but pay particular attention to calls to CMutex's constructors
CMutex (BOOL binitiallyown = FALSE, LPCTSTR lpszName = null, lpsecurity_attributes Lpsaattribute = null)
Unused parameters can not be filled out, random fill will appear some unexpected results.

Signal Volume (semaphores)


Semaphore objects synchronize threads differently than in the previous methods, and the signal allows multiple threads to use shared resources at the same time as the PV operation in the operating system. It indicates the maximum number of threads concurrently accessing the shared resource. It allows multiple threads to access the same resource at the same time, but needs to limit the maximum number of threads that access this resource at the same time. When you create a semaphore with CreateSemaphore (), you indicate both the maximum allowable resource count and the current available resource count. In general, the current available resource count is set to the maximum resource count, and each additional thread accesses the shared resource, the current available resource count is reduced by 1, and the semaphore signal can be emitted as long as the current available resource count is greater than 0. However, the current available count is reduced to 0 o'clock indicating that the number of threads currently occupying the resource has reached the maximum allowable number, and the semaphore signal will not be able to be emitted when other threads are allowed to enter. After the thread has finished processing the shared resource, the current available resource count should be added by 1 at the same time as the ReleaseSemaphore () function is left. At any time the currently available resource count is never greater than the maximum resource count.
The concept of PV operation and signal volume is presented by Dutch scientist E.w.dijkstra. The semaphore S is an integer, s greater than or 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, then the process is blocked into the queue corresponding to the signal, and then transferred to the process scheduling.
V Operations Release Resources:
(1) s plus 1;
(2) If the sum result is greater than 0, the process will continue to execute;
(3) If the sum result is less than or equal to zero, a wait process is awakened from the waiting queue of the signal and then returned to the original process to continue or transfer to the process schedule.

The semaphore contains several operation Primitives:
CreateSemaphore () Create a semaphore
OpenSemaphore () Open a semaphore
ReleaseSemaphore () Release semaphore
WaitForSingleObject () wait for the semaphore
Events (Event)

The event object can also maintain thread synchronization by notifying the operation. And can be implemented in different processes of thread synchronization operations.
The semaphore contains several operation Primitives:
CreateEvent () Create a semaphore
OpenEvent () Open an event
SetEvent () Reset Event
WaitForSingleObject () waits for an event
WaitForMultipleObjects () waits for multiple events
WaitForMultipleObjects function Prototypes:
WaitForMultipleObjects (
In DWORD ncount,//wait handle number
In CONST HANDLE *lphandles,//pointer to handle array
In BOOL bWaitAll,//whether to completely wait for the flag
In DWORD dwmilliseconds//wait Time

The parameter ncount specifies the number of kernel objects to wait for, and the array that holds the kernel objects is pointed to by Lphandles. The fWaitAll specifies two wait modes for the specified Ncount kernel object, True when all objects are notified and the function returns, False if any of them are notified. The role of dwmilliseconds here is exactly the same as in the WaitForSingleObject (). If the wait timeout occurs, the function returns WAIT_TIMEOUT.

Summarize:
1. The mutex is very similar to the critical section, but the mutex can be named, which means it can be used across processes. So creating mutexes requires more resources, so using a critical section just to be used within a process can bring speed advantages and reduce resource usage. Because the mutex is a cross-process mutex once created, it can be opened by name.
2. Mutexes (mutexes), semaphores (Semaphore), events can be used across processes to synchronize data operations, while other objects are not related to data synchronization operations, but for processes and threads, if the process and thread are running in a state that is not signaled, signaled state after exiting. So you can use WaitForSingleObject to wait for processes and threads to exit.
3. The mutex can be used to specify that the resource is exclusive, but if one of the following cases can not be handled by mutual exclusion, for example, now a user buys a three concurrent Access License database system, depending on the number of access licenses purchased by the user to determine how many threads/processes can simultaneously perform database operations, At this time, if the use of mutual exclusion is no way to complete this requirement, the Beacon object can be said to be a resource counter.

"Go" "Linux" critical zone, mutex, Semaphore, event difference

Related Article

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.