Windows Thread Synchronization Summary

Source: Internet
Author: User

Windows thread Synchronization

Thread synchronization for Windows can be implemented by using mutually exclusive objects, or by using event objects, key code snippets.

1 Event objects Implement thread synchronization

<1>event Object creation function

The event object's creation event object belongs to the kernel object, which contains a Boolean value with three members: A Boolean value that uses a count, whether it is auto-reset or manual reset, and a notification state.

HANDLE CreateEvent (         lpsecurity_attributeslpeventattributes,         boolbmanualreset,         boolbinitialstate,         lpcstrlpname);

bManualReset: True represents an event object that is manually reset, and False represents an automatically reset event object. If the event object is manually reset, then when the thread waits to take ownership of the object, it needs to call the ResetEvent function to set the state of the object to a non-notification state, and all the threads to be scheduled threads, and if the thread gets ownership of the object, when it is automatically reset the state. The system automatically sets the object to a no notification state.

binitialstate: True indicates that the initial state of the event object is signaled, and false indicates that the initial state is not signaled.

<2> set the status of the signal

The status of the signal can be set to a signal and no signal two states, the signal is set to call the function

BOOL SetEvent (HANDLE hevent);

Setting to no signal requires calling the following function:

BOOL resetevent (HANDLE hevent);

<3> conditions for thread synchronization using event objects

The condition is that the bManualReset parameter must be set to False, which is the event object that is automatically reset.

Analysis:

If the bManualReset object is set to True, then if the binitialstate is set to false, then the child thread waiting for the event object will never wait for the events object to become signaled. Because there is no manual reset, it does not turn into a signaled state.

If the binitialstate is set to true, then the child thread can compete for the ownership of the event, even if a thread obtains ownership, but the event object is always signaled, so the other thread can switch over at any time, which is also undesirable.

So if the thread acquires the ownership of the object immediately after ResetEvent the event object into a no-signal feasible? The answer is no, because there may be a situation: the signal has not yet come to a sudden change, the time slice has moved to another thread, because the signal is in the notification state, then the switch to the thread can also get the event object ownership, and then into its protected code area, This causes more than one thread to enter their respective protected code area at the same time, thus breaking the synchronization.

Conclusion:

If you want to use the event object to implement thread synchronization, you must set the bManualReset parameter to False, which automatically resets the object when it is the event object.

Sample program:

#include <iostream> #include <windows.h>using namespace std; HANDLE gevent =null;int tickets= 100; DWORD WINAPI Fun1proc (lpvoid lpparameter);D word WINAPI fun2proc (lpvoid lpparameter); void Main () {HANDLE Hthrea         D1 = NULL;          HANDLE hThread2 = NULL;         Gevent =createevent (null,true,true,null);         Gevent =createevent (null,false,true,null);         CreateThread (Null,0,fun1proc,null,0,null);         CreateThread (Null,0,fun2proc,null,0,null);         CloseHandle (HTHREAD1);         CloseHandle (HTHREAD2);         Sleep (4000); CloseHandle (gevent);} DWORD WINAPI Fun1proc (LPVOID lpparameter) {while (TRUE) {WaitForSingleObject (gevent,in                   finite);                   ResetEvent (gevent);                            if (tickets>0) {Sleep (1);                            cout<< "Thread 1 is selling tickets:" <<tickets--<<endl; SetEvent (GEVENT);                            } else {SetEvent (gevent);                   Break }} Return0;} DWORD WINAPI Fun2proc (LPVOID lpparameter) {while (TRUE) {WaitForSingleObject (gevent,in                   finite);                   ResetEvent (gevent);                            if (tickets>0) {Sleep (1);                            cout<< "Thread 2 is selling tickets:" <<tickets--<<endl;                   SetEvent (gevent);                            } else {SetEvent (gevent);                   Break }} Return0;}

2 Key Code Snippets

The critical code snippet is also called the critical section, which works in user mode. It refers to a small piece of code that must monopolize access to certain resources before the code can execute.

Its flow is as follows:


Example code:

#include <iostream> #include <windows.h>using namespace std; DWORD WINAPI Fun1proc (lpvoid lpparameter);D word WINAPI fun2proc (lpvoid lpparameter);    Critical_sectiongcs;int tickets = 100;         void Main () {HANDLE hThread1 = NULL;          HANDLE hThread2 = NULL;         HThread1 =createthread (null,0,fun1proc,null,0,null);         HThread2 =createthread (null,0,fun2proc,null,0,null);         CloseHandle (HTHREAD1);         CloseHandle (HTHREAD2);         InitializeCriticalSection (&gcs);         Sleep (4000); DeleteCriticalSection (&gcs);} DWORD WINAPI Fun1proc (lpvoidlpparameter) {while (TRUE) {entercriticalsection (&AMP;GC                   s);                   Sleep (1); if (tickets>0) {cout<< "Thread1 is selling ticket:" <<tickets--&                            lt;<endl;                   LeaveCriticalSection (&gcs);                 } else  {leavecriticalsection (&gcs);                   Break }} Return0;} DWORD WINAPI Fun2proc (lpvoidlpparameter) {while (TRUE) {entercriticalsection (&AMP;GC                   s);                   Sleep (1); if (tickets>0) {cout<< "Thread2 is selling ticket:" <<tickets--&                            lt;<endl;                   LeaveCriticalSection (&gcs);                            } else {leavecriticalsection (&gcs);                   Break }} Return0;}

Comparison of 33 thread synchronization methods

<1>mutex,event is a kernel object, and kernel objects are slow to thread synchronization

<2>criticalsection belongs to user mode, synchronization speed is slow

<3>mutex,event synchronization needs to use the WaitForSingleObject to wait for the signal to become valid when entering the core code segment, and so on when the signal needs to be set to a signal state so that other threads into the core code snippet.

CriticalSection is used in a comparative image of the way EnterCriticalSection and LeaveCriticalSection.

<4>mutex,event CloseHandle to close the kernel object in the end, CriticalSection uses DeleteCriticalSection to delete the object.

<5> Overall there are three different ways to claim that you have exclusive resources in a sign or other way, and then release ownership after using the resources.

Windows Thread Synchronization Summary

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.