Mutex synchronization-differences between critical zones, mutex counts, semaphores, and events

Source: Internet
Author: User

Control Methods for mutual exclusion of four processes or threads
1. critical section: accesses public resources or code segments through multi-thread serialization, which is fast and suitable for controlling data access.
2. mutex: designed to coordinate separate access to a shared resource.
3. semaphore: designed to control a limited number of user resources.
4. Event: it is used to notify the thread that some events have occurred and start subsequent tasks.

Critical Section)

A convenient way to ensure that only one thread can access data at a certain time point. Only one thread is allowed to access Shared resources at any time. If multiple threads attempt to access the critical section at the same time, all other threads attempting to access the critical section will be suspended and will continue until the thread enters the critical section. After the critical section is released, other threads can continue to seize it and use the atomic method to share resources.

The critical section contains two operation primitives:
Entercriticalsection () enters the critical section
Leavecriticalsection () leaves the critical section
After the entercriticalsection () Statement is executed, no matter what happens after the Code enters the critical section, make sure that the matching leavecriticalsection () can be executed. Otherwise, the shared resources protected in the critical section will never be released. Although the synchronization speed in the critical section is very fast, it can only be used to synchronize threads in the current process, but not to synchronize threads in multiple processes.

MFC provides many functions and complete classes. I use MFC to implement the critical section. MFC provides a class of ccriticalsection for the critical section. It is very easy to use this class for thread synchronization. You only need to use the ccriticalsection class member functions lock () and unlock () in the thread function to calibrate the protected code snippet. The resource used by the lock () descendant code is automatically considered to be protected in the critical section. After unlock, other threads can access these resources.

Mutex)

The mutex is similar to that in the adjacent zone. Only threads with mutex objects have the permission to access resources. Because there is only one mutex object, therefore, it is determined that the shared resource will not be accessed by multiple threads at the same time under any circumstances. The thread occupying the resource should hand over the mutex object after the task is processed, so that other threads can access the resource after obtaining it. Mutex is more complex than that in the critical section. Because mutex can not only achieve secure resource sharing in different threads of the same application, but also achieve secure resource sharing among threads of different applications.

The mutex contains several operation primitives:
Createmutex () creates a mutex
Openmutex () opens a mutex
Releasemutex () releases mutex
Waitformultipleobjects () waits for the mutex object

Similarly, MFC provides a cmutex class for mutex. It is very easy to use the cmutex class to implement mutex operations, but pay special attention to calling the cmutex constructor.
Cmutex (bool binitiallyown = false, lpctstr lpszname = NULL, lpsecurity_attributes lpsaattribute = NULL)

You cannot enter unnecessary parameters. If you enter unnecessary parameters, unexpected running results may occur.
Semaphores)

The method for synchronizing semaphore objects to threads is different from the previous methods. Signals allow multiple threads to use shared resources at the same time, which is the same as PV operations in the operating system. It specifies the maximum number of threads simultaneously accessing shared resources. It allows multiple threads to access the same resource at the same time, but it needs to limit the maximum number of threads that can access the resource at the same time. When using createsemaphore () to create a semaphore, you must specify the maximum allowed resource count and the current available resource count. Generally, the current available resource count is set to the maximum Resource Count. Each time a thread is added to access a shared resource, the current available resource count is reduced by 1, as long as the current available resource count is greater than 0, a semaphore signal can be sent. However, when the current available count is reduced to 0, it indicates that the number of threads currently occupying resources has reached the maximum allowed number,
Other threads cannot be allowed to enter. At this time, the semaphore signal cannot be sent. After processing shared resources, the thread should use the releasesemaphore () function to increase the number of currently available resources by 1 while leaving. The current available resource count cannot exceed the maximum resource count at any time.

PV operations and semaphores are all proposed by Dutch scientist E. W. Dijkstra. Semaphore s is an integer. When S is greater than or equal to zero, the number of resource entities available for concurrent processes in the table. If S is less than zero, it indicates the number of processes waiting to use shared resources.

P operation resource application:
(1) s minus 1;
(2) If s minus 1 is still greater than or equal to zero, the process continues to run;
(3) If s minus 1 is less than zero, the process is blocked and enters the queue corresponding to the signal, and then transferred to the process scheduling.
V operation to release resources:
(1) s plus 1;
(2) If the sum result is greater than zero, the process continues to execute;
(3) If the sum result is less than or equal to zero, a waiting process is awakened from the waiting queue of the signal, and then the original process is returned for further execution or transfer to process scheduling.

The semaphore contains several operation primitives:
Createsemaphore () to create a semaphore
Opensemaphore () opens a semaphore
Releasesemaphore () Release semaphores
Waitforsingleobject () waiting for semaphores
Event)

Event objects can also be synchronized by means of notification operations. In addition, threads in different processes can be synchronized.
The semaphore contains several operation primitives:
Createevent () to create a semaphore
Openevent () opens an event
Setevent () reset event
Waitforsingleobject () waits for an event
Waitformultipleobjects () waits for multiple events
Waitformultipleobjects function prototype:
Waitformultipleobjects (
In DWORD ncount, // number of pending handles
In const handle * lphandles, // point to the handle Array
In bool bwaitall, // indicates whether to wait completely
In DWORD dwmilliseconds // wait time
)
The ncount parameter specifies the number of kernel objects to wait for. The array of these kernel objects is pointed by lphandles. Fwaitall specifies the two waiting methods for the specified ncount kernel object. If it is true, the function returns only when all objects are notified, if this parameter is set to false, only one of them is notified. Dwmilliseconds serves exactly the same purpose as waitforsingleobject. If the wait times out, the function returns wait_timeout.
Summary:
1. The mutex function is very similar to that of the critical zone, but the mutex can be named, that is, it can be used across processes. Therefore, creating mutex requires more resources. Therefore, if you only want to use it within a process, using the critical section will bring speed advantages and reduce resource occupation. Because the mutex is a cross-process mutex, once created, it can be opened by name.

2. mutex, semaphore, and event can all be used by a process to synchronize data. Other objects have nothing to do with data synchronization, but for the process and thread, if the process and thread are in the running status, there is no signal, and there is a signal after exiting. Therefore, you can use waitforsingleobject to wait for the process and thread to exit.

3. you can specify how resources are exclusive by means of mutex. However, if the following problem occurs, the resource cannot be processed by means of mutex, for example, a user buys a database system with three concurrent access permits, you can determine how many threads/processes can perform database operations at the same time based on the number of access licenses purchased by the user. At this time, if the mutex is used, this requirement cannot be fulfilled, a traffic signal object is a resource calculator.

 

From: http://blog.csdn.net/seawt/archive/2010/09/08/5870288.aspx

 

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.