) Critical section, mutex, semaphores, and events (thread synchronization)

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
There is a line
All other threads that attempt to access this critical section will be suspended until they exit. After the critical section is released, other threads can continue to seize it and operate it in atomic mode.
For the purpose of sharing resources.
The critical section contains two operation primitives:
Entercriticalsection () enters the critical section
Leavecriticalsection () leaves the critical section
Entercriticalsection ()
After the statement is executed, the Code will enter the critical section. No matter what happens, make sure that it matches
All 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 for synchronization.
Threads in the process, but cannot be used to synchronize threads in multiple processes.
MFC provides many functions and complete classes. I use MFC to implement the critical section. MFC provides a critical section
Ccriticalsection class, which is used for thread synchronization?
Very simple. You only need to use the ccriticalsection class member functions lock () and unlock () in the thread function to calibrate the protected code snippet. Lock () descendant
The resource used by the Code is automatically considered to be protected in the critical section. After unlock, other threads can access these resources.
Mutex)

Mutex
The zone is similar. Only threads with mutex objects have the permission to access resources. Because there is only one mutex object, it determines that the shared resources will not be shared 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 be used not only in the same
Resources can be securely shared among different threads of an application, and resources can be securely shared 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 indicates simultaneous access and sharing
Resource thread
The maximum number. 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. Create a semaphore with createsemaphore ()

The maximum allowed resource count and the current available Resource Count must be specified at the same time. 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

It will be 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
Add 1 to the Resource Count. 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
)
Parameter
The number ncount specifies the number of kernel objects to wait for. The array of these kernel objects is pointed by lphandles. Fwaitall specifies the ncount kernel.
The two wait methods of the object are specified. If the value is true, the function returns only when all objects are notified. If the value is false, the function returns if any of the objects 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 similar to that of the critical section, but the mutex can be named, that is, it can be used across processes. Therefore, creating mutex requires more resources.
Using a critical section 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.
Mutex, semaphore, and event can all be used by a process to synchronize data. Other objects have nothing to do with data synchronization.

For processes and threads, if the processes and threads are in the running state, they are in the non-signal State and there is a signal state after exiting. So you can use waitforsingleobject to wait for the process and
The thread exits.
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, if a user buys a database system with three concurrent access permits

Depending on the number of access licenses purchased by the user, the number of threads/processes that can perform database operations at the same time is determined. At this time, if the mutex is used, this requirement cannot be fulfilled, a traffic signal object is a resource count.
.

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.