Windows thread Synchronization

Source: Internet
Author: User
Tags semaphore

Windows critical section, kernel event, mutex, semaphore.

Critical section, kernel event, mutex, semaphore, all can complete the thread synchronization, here put their respective function call, structure definition, as well as apply the situation to make a summary.

critical Section :

Scope of application: It can only synchronize threads in one process and cannot synchronize across processes. It is generally used for fast synchronization of code within a single process , which is relatively efficient.

Related structure: critical_section _critical

Related methods:

/* Initialize, the function that is called first. There's nothing to say, general Windows programming has a similar initialization method */

InitializeCriticalSection (& _critical)

/* Release the resource and make sure it is called when _critical is not used, typically when the program exits. If you want to use _critical later, you need to call InitializeCriticalSection again.

*/

DeleteCriticalSection (& _critical)

/*

Protect the code. After calling this function, the other threads of his later resources will not be accessible.

*/

EnterCriticalSection (& _critical)

/*

Leave the critical section to indicate that other threads are able to come in. Note that entercritical and leavecrticalsection must be paired! Unless, of course, you're trying to lock it up!

*/

LeaveCriticalSection (& _critical)

Code Demo

Critical section
#include "stdafx.h"
int thread_count = 0;
/*mutex mutex1;*/
critical_section G_cs;
DWORD CALLBACK Thread_proc (LPVOID params)
{
for (int i = 0; i <; ++i)
{
Synchronized (MUTEX1)
entercriticalsection (&g_cs);
{
for (char c = ' A '; c <= ' Z '; ++c)
{
printf ("%c", c);
}
printf ("\ n");
}
leavecriticalsection (&g_cs);
}
thread_count--;
return 0;
}

int _tmain (int argc, _tchar* argv[])
{
initializecriticalsection (&g_cs);
Thread_count = 4;
CreateThread (0, 0, thread_proc, 0, 0, 0);
CreateThread (0, 0, thread_proc, 0, 0, 0);
CreateThread (0, 0, thread_proc, 0, 0, 0);
CreateThread (0, 0, thread_proc, 0, 0, 0);
while (Thread_count)
Sleep (0);
GetChar ();
deletecriticalsection (&g_cs);
return 0;

Kernel events:

Scope of application: More for communication between threads, can be synchronized across processes.

Related structure: HANDLE hevent;

Related methods:

/*

Initialize the method, create an event object, the first parameter represents the security attribute, in general, it is OK to encounter this type of parameter directly to empty, the second parameter is a manual reset. (Kernel time has two modes of operation: manual reset and automatic reset.) The difference is mentioned below. )。 The third parameter is the initial state, and the fourth parameter event name.

*/

hevent = CreateEvent (null,false,false,null);

/*

Waits for a single event to be set, that is, the thread will block in this function until the event is placed, SetEvent.

If the event is automatically reset, the system automatically calls ResetEvent (hevnet) After this function returns and resets the event to ensure that other threads cannot access it.

If it is a manual reset event, the other threads of the system can continue to access it after this function returns.

The second parameter describes the wait event, and Inifinet indicates waiting.

*/

Watiforsingleobject (hevent,inifinet)

/*

The set event, as long as the event is placed in the thread to access. That is, Watiforsingleobject (hevent,inifinet) returns

*/

Serevent (hevent);

/*

Resets the event so that Watiforsingleobject () does not return

*/

ResetEvent (hevent)

/*

Waits for multiple event objects. 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. If you return a value from Wait_object_0 to Wait_object_0+ncount-1, the state of all the specified objects is the state of the notification (when fWaitAll is true) or to subtract wait_object_ 0 The index of the object from which the notification occurred (when fWaitAll is false)

*/

Waitformultiobjects (DWORD ncount,//wait handle number

CONST HANDLE *lphandles,//handle array first address

BOOL fWaitAll,//wait sign

DWORD dwmilliseconds//wait time interval)

/*

Opens a named event object that can be used to synchronize across processes

*/

HANDLE OpenEvent (
DWORD dwdesiredaccess,//Access flag
BOOL bInheritHandle,//Inheritance flag
LPCTSTR lpname//Pointer to event object name
);

Test code

Kernel events
#include "stdafx.h"
/* #include "Mutex.h" */
int thread_count = 0;
/*mutex mutex1;*/
/*critical_section g_cs;*/
HANDLE hevent;
DWORD CALLBACK Thread_proc (LPVOID params)
{
for (int i = 0; i <; ++i)
{
Synchronized (MUTEX1)
EnterCriticalSection (&g_cs);

WaitForSingleObject (Hevent,infinite);
{
for (char c = ' A '; c <= ' Z '; ++c)
{
printf ("%c", c);
Sleep (1);
}
printf ("\ n");
}
SetEvent (hevent);
LeaveCriticalSection (&g_cs);
}
thread_count--;
return 0;
}

int _tmain (int argc, _tchar* argv[])
{
InitializeCriticalSection (&g_cs);
hevent = CreateEvent (null,false,false,null);
SetEvent (hevent);
Thread_count = 4;
CreateThread (0, 0, thread_proc, 0, 0, 0);
CreateThread (0, 0, thread_proc, 0, 0, 0);
CreateThread (0, 0, thread_proc, 0, 0, 0);
CreateThread (0, 0, thread_proc, 0, 0, 0);
while (Thread_count)
Sleep (0);
GetChar ();
DeleteCriticalSection (&g_cs);
return 0;
}

Mutex Amount:

Scope of application: can be synchronized across processes, but also to ensure that only one instance of the program runs (create named mutex) , can also be used to synchronize between threads.

Related structure: HANDLE Hmutex;

Related methods:

/*

Create mutex, initialize the work

Parameter one is a security option and is generally empty

Parameter two indicates whether the current mutex belongs to a thread and is generally empty

The name of the three-mutex parameter, which needs to be set if you need to synchronize across processes or if you need to ensure that only one instance of the program is running, other conditions are generally empty.

*/

CreateMutex (Null,false,null)

WaitForSingleObject (hmutex,inifinet);//Same Event object

/*

Frees the mutex so that other threads can access it.

*/

ReleaseMutex (Hmutex)

/*

The return value of the wait function is no longer the usual wait_object_0 (for the WaitForSingleObject () function) or wait_object_0 to wait_object_0+ when the mutex object notifies the call waiting function to return. A value between nCount-1 (for the WaitForMultipleObjects () function), but instead returns a Wait_abandoned_0 (for the WaitForSingleObject () function) or Wait_ A value between Abandoned_0 to Wait_abandoned_0+ncount-1 (for the WaitForMultipleObjects () function).

*/

Waitformultiobjects (DWORD ncount,//wait handle number

CONST HANDLE *lphandles,//handle array first address

BOOL fWaitAll,//wait sign

DWORD dwmilliseconds//wait time interval)

/*

Open a named mutex that has already been created for cross-process synchronization

*/

HANDLE OpenMutex (
DWORD dwdesiredaccess,//Access flag
BOOL bInheritHandle,//Inheritance flag
LPCTSTR lpname//Mutex object name
);

Test Demo

Mutex Amount
#include "stdafx.h"
/* #include "Mutex.h" */
int thread_count = 0;
/*mutex mutex1;*/
/*critical_section g_cs;*/
HANDLE hevent;
HANDLE Hmutex;
DWORD CALLBACK Thread_proc (LPVOID params)
{
for (int i = 0; i <; ++i)
{
Synchronized (MUTEX1)
EnterCriticalSection (&g_cs);
WaitForSingleObject (Hmutex,infinite);
WaitForSingleObject (Hevent,infinite);
//{
for (char c = ' A '; c <= ' Z '; ++c)
{
printf ("%c", c);
Sleep (1);
}
printf ("\ n");
//}
SetEvent (hevent);
ReleaseMutex (Hmutex);
LeaveCriticalSection (&g_cs);
}
thread_count--;
return 0;
}

int _tmain (int argc, _tchar* argv[])
{
InitializeCriticalSection (&g_cs);
hevent = CreateEvent (null,false,false,null);
SetEvent (hevent);
Hmutex = CreateMutex (null,false,null);
Thread_count = 4;
CreateThread (0, 0, thread_proc, 0, 0, 0);
CreateThread (0, 0, thread_proc, 0, 0, 0);
CreateThread (0, 0, thread_proc, 0, 0, 0);
CreateThread (0, 0, thread_proc, 0, 0, 0);
while (Thread_count)
Sleep (0);
GetChar ();
DeleteCriticalSection (&g_cs);
return 0;
}

Note : All synchronization operations must be in pairs, that is, to lock an object, be sure to release an object. However, if an exception occurs quickly in the protected code, the program flow unexpectedly jumps instead of releasing the lock object, causing the program to enter a deadlock. Therefore, the necessary exception handling in the program is required, but there is no finally such keyword in C + + to ensure that code that executes regardless of whether an exception occurs is fast. What about that? This requires the exception of C + + some tips to deal with ...

Windows thread Synchronization

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.