1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
|
// TesyMutex.cpp*: définit le point d'entrée pour l'application console.
//
#include "stdafx.h"
#include <stdio.h>
#include <winsock2.h>
#include <WinBase.h>
HANDLE SemMutex;
void Funct1 (void)
{
DWORD dwWaitResult;
dwWaitResult = WaitForSingleObject (SemMutex, // handle to mutex
INFINITE // no time-out interval
);
printf ("Thread 1: WaitForSingleObject() returns %d\n", dwWaitResult);
// ReleaseMutex (SemMutex);
}
void Funct2 (void)
{
DWORD dwWaitResult;
Sleep (2000);
dwWaitResult = WaitForSingleObject (SemMutex, // handle to mutex
INFINITE // no time-out interval
);
printf ("Thread 2: WaitForSingleObject() returns %d\n", dwWaitResult);
// ReleaseMutex (SemMutex);
}
int _tmain(int argc, _TCHAR* argv[])
{
char c;
HANDLE HandleTh1;
HANDLE HandleTh2;
DWORD ECRthreadID1;
DWORD ECRthreadID2;
SemMutex = CreateMutex (NULL, // default security attributes
FALSE, // initially not owned
NULL // unnamed mutex
);
if(SemMutex == NULL)
{
// An error has occurred
printf ("Error to create semaphore\n");
return 0;
}
HandleTh1 = CreateThread (NULL, //Choose default security
0, //Default stack size
(LPTHREAD_START_ROUTINE) &Funct1, //Routine to execute
NULL, // No parameter
0, // Immediately run the thread
&ECRthreadID1 //Thread Id
);
HandleTh2 = CreateThread (NULL, //Choose default security
0, //Default stack size
(LPTHREAD_START_ROUTINE) &Funct2, //Routine to execute
NULL, // No parameter
0, // Immediately run the thread
&ECRthreadID2 //Thread Id
);
WaitForSingleObject (HandleTh2, INFINITE);
WaitForSingleObject (HandleTh1, INFINITE);
CloseHandle (SemMutex);
scanf ("Press any key to exit", &c);
return 0;
} |
Partager