Windows thread Synchronization

Source: Internet
Author: User
Tags exit in semaphore

First, preface

Previously in the project, because of the need to use multi-threading, multithreading can improve the efficiency of execution, but also bring the problem of thread synchronization, it is hereby summarized as follows.

Second, Windows thread synchronization mechanism

The Windows thread synchronization mechanism is commonly used in several ways: Event, Critical section, Mutex, Semaphore.

1.Critical section (critical area)

Scope of application: a single process between the threads used for exclusive possession

Feature: not a Kernel object, the most efficient of the four mechanisms mentioned here ( Note: Because the critical section is non-kernel object, can be maintained in user space, there is no handle, then can not use waitformultipleobjects to prevent deadlock problem ). Unable to monitor whether the thread was discarded. If the program crash or exit in the middle of critical sections does not call LeaveCriticalSection, the result is that the kernel corresponding to the thread cannot be freed and the thread becomes a dead thread.

Critical section correlation function:

1     // The function function initializes a critical resource object.  2     VOID entercriticalsection (lpcritical_section lpcriticalsection);      // Enter the critical section 3     VOID leavecriticalsection (lpcritical_section lpcriticalsection);      // leave the critical section 4     VOID deletecriticalsection (lpcritical_section lpcriticalsection);     // destroying critical areas
2.Mutex (Mutex core object)

Scope of application: between different threads for exclusive possession

Attributes: The core object, having a handle, having the owner, which thread owns the mutex, takes ownership of the mutex, and the non-owner executes the ReleaseMutex error. mutexes can be synchronized across processes .

Mutex correlation function:

A. Create

1 HANDLE CreateMutex (2 lpsecurity_attributes lpmutexattributes, // security attribute structure pointer 3 BOOL Binitialowner, // whether to occupy the mutex 4 lpctstr lpname // Set the name of the mutex object 5 );

B. Opening an existing named mutex

1 HANDLE OpenMutex (2//  access3//  inheritance option 4 // Object Name 5 );

C. Possession/acquisition of mutex

1 DWORD WaitForSingleObject (2HANDLE hhandle,3DWORD dwmilliseconds  4 );

D. Releasing mutexes

1 BOOL wianpi ReleaseMutex (2HANDLE hmutex3 );
3.Event (Event kernel object)

Scope of application: used to control the reception of the object signal, often combined with the signal system

Attributes: core objects, with handles, have two different types of event objects. One is a manually reset event, and the other is an automatically reset event . When a manually reset event is notified (signaled), all threads waiting for the event become scheduled threads until ResetEvent is called, and the event becomes unsignaled. When an automatically reset event is notified, only one thread in the thread that waits for the event becomes a scheduler thread, and the event is automatically changed to unsigned.

After the setevent, the automatic set-up event remains in the state until there is a wait event and then automatically resets. Manual reset event, the signaled state is saved until ResetEvent is called.

After PulseEvent, for a manual reset event, all current threads (if any) are released and the event is reset to unsigned. (Not recommended)

WaitForMultipleObjects, the event is released only when all the waiting events are at the same time, and automatically resets after the thread is released for automatic reset.

Related functions: CreateEvent, Openevent,setevent, ResetEvent, PulseEvent.

4.Semaphore (Signal core object)

Scope of application: used to limit resource consumption

Features: core object, no owner, any thread can be freed . Semaphore (Semaphore) kernel objects synchronize threads differently than in the previous methods, which allow multiple threads to access the same resource at the same time, but need 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.
Function: CreateSemaphore opensemaphore ReleaseSemaphore

Comparison between mutex and critical section

1.Mutex if the terminated thread is thrown, it will be a messenger, the other threads will not block forever, while the critical section is not, if the terminated thread is not released, then the other waiting threads will be blocked forever.

2.Mutex is the kernel object, there is a timeout mechanism (with a handle, can be implemented using the WAITFOR_ function), and CS non-kernel object, no handle, cannot use the WAITFOR series functions, implement the timeout mechanism, can only use tryentercriticalsection polling.

3.Mutex can be named, can be synchronized across the process, CS not.

4.Mutex can immediately specify ownership of the mutex at the time of creation, and CS does not.

5.CS because the non-kernel object, do not need to switch the state of the program to run frequently to the kernel mentality, all CS almost always faster than the mutex.

Non-kernel objects (CS) vs. kernel objects (Other):

1. Kernel object has handle can use WaitForMultipleObjects, wait for multiple objects at one time, avoid deadlock;

2.CS no handle, no use, you need to consider the problem of preventing deadlock. ( to CS number, in a certain order to obtain, break the formation of the ring ).

3. For the above several named Kernel synchronization objects, can be cross-process synchronization, and,CS is non-kernel object, directly constructs in the user space , fast and brings another problem, that is, there is no way to synchronize across processes .

Iv. PostScript

For the use of CS, we generally use the form of internal classes , to prevent exceptions when there is no leavecriticalsection.

This may not be summed up enough, hope to be able to summarize later. In addition, this blog post references the http://www.cnblogs.com/luxiaoxun/archive/2012/10/10/2717765.html

Windows thread Synchronization

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.