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 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
| // TestMutex.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <stdio.h>
#include <winsock2.h>
#include <WinBase.h>
HANDLE SemMutex;
void Funct1 (void)
{
int err = 0;
DWORD dwWaitResult;
SemMutex = CreateMutex (NULL, // default security attributes
FALSE, // initially not owned
NULL // unnamed mutex
);
if (SemMutex == NULL)
{
// An error has occurred
err = 1;
}
dwWaitResult = WaitForSingleObject (SemMutex, // handle to mutex
INFINITE // no time-out interval
);
/*if (ReleaseMutex (SemMutex) != 0)
{
err = 1;
}
if (CloseHandle (SemMutex) != 0)
{
err = 1;
}*/
}
void Funct2 (void)
{
int err = 0;
DWORD dwWaitResult;
Sleep (2000);
SemMutex = CreateMutex (NULL, // default security attributes
FALSE, // initially not owned
NULL // unnamed mutex
);
if (SemMutex == NULL)
{
// An error has occurred
err = 1;
}
dwWaitResult = WaitForSingleObject (SemMutex, // handle to mutex
INFINITE // no time-out interval
);
/*if (ReleaseMutex (SemMutex) != 0)
{
err = 1;
}
if (CloseHandle (SemMutex) != 0)
{
err = 1;
}*/
}
int _tmain(int argc, _TCHAR* argv[])
{
HANDLE HandleTh1;
HANDLE HandleTh2;
DWORD ECRthreadID1;
DWORD ECRthreadID2;
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
);
HandleTh1 = 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
);
Sleep (30000);
return 0;
} |
Partager