We often need to perform thread synchronization and collaboration when writing multi-threaded applications. Let's use mutex to synchronize threads. See Code implementation and annotation analysis.
/* Header file */# include <windows. h> # include <stdio. h>/* constant definition */# define num_threads4/* global variable */DWORD dwcounter = 0; handle hmutex;/* function declaration */void usemutex (void ); DWORD winapi mutexthread (lpvoid lpparam ); /************************************* int main (void) * function demonstration ** the parameter is not ******************************** * *****/INT main () {usemutex ();} /************************************ void usemutex (void) * demonstrate how to use mutex ** The parameter is not *********************************** * **/void usemutex (void) {int I; handle hthread; # ifdef mutex // create mutexhmutex = createmutex (null, // Default Security Attribute false, // The Initialization is not null ); // If (hmutex = NULL) {printf ("createmutex error: % d \ n", getlasterror ());} # endif // create multiple threads for (I = 0; I <num_threads; I ++) {hthread = createthread (null, 0, mutexthread, null, 0, null ); if (hthread = NULL) {printf ("createth Read failed (% d) \ n ", getlasterror (); Return ;}} sleep (1000 );} /************************************ DWORD winapi mutexthread (lpvoid lpparam) * function thread functions, the read shared memory ** parameter does not use ******************************** * *****/DWORD winapi mutexthread (lpvoid lpparam) {# ifdef mutex DWORD dwwaitresult; dwwaitresult = waitforsingleobject (hmutex, // handle infinite); // infinite waiting switch (dwwaitresult) {Case wait_object_0: # endif // wait for a random long time, The waiting time of each thread will be inconsistent sleep (RAND () % 100); // obtain the mutex object and access the shared data printf ("counter: % d \ n ", dwcounter); // The mutex object ensures that only one thread accesses dwcounterdwcounter ++ at the same time; # ifdef mutex // release mutexif (! Releasemutex (hmutex) {printf ("release mutex error: % d \ n", getlasterror ();} break; default: printf ("Wait error: % d \ n ", getlasterror (); exitthread (0) ;}# endifreturn 1 ;}