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
|
// TestEvent.cpp
#include "stdafx.h"
#include "TestEvent.h"
// Global
HANDLE hEventHandle = NULL;
HANDLE hThreadHandle = NULL;
void MyDebugOut(TCHAR *text, int v) //should be smarter
{
SYSTEMTIME st;
TCHAR buf[256];
GetLocalTime(&st);
swprintf(buf, (sizeof(buf) / sizeof(buf[0])) - 1, _T("%02d:%02d:%02d|%03d %s %d\n"),
st.wHour, st.wMinute, st.wSecond, st.wMilliseconds, text, v);
OutputDebugString(buf);
}
DWORD WINAPI ThreadActionFunction(LPVOID lParam)
{
int i = 0;
int z = 1;
DWORD resWait;
do
{
i++;
MyDebugOut(_T("Thread: wait for event i="), i);
resWait = WaitForSingleObject(hEventHandle, INFINITE);
MyDebugOut(_T("Thread: run because an event, resWait="), resWait);
if ( !ResetEvent(hEventHandle) ) //release for next turn
{
MyDebugOut( _T("Thread: ResetEvent failure(7)! i=") , i );
exit(-1);
}
/* some thread acton*/
Sleep(100);
} while (z);
MyDebugOut(_T("Thread: loop exited on i="), i);
return -1;
}
int APIENTRY _tWinMain(_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPTSTR lpCmdLine,
_In_ int nCmdShow)
{
hEventHandle = CreateEvent( // to stop thread while starting
NULL, // default security attributes
false, // auto reset mode
false, // not signaled
NULL);
if ( !hEventHandle )
{
MyDebugOut(_T("main: CreateEvent failure! "), -1);
exit(-1);
}
MyDebugOut(_T("main: Initial block of thread on start"), 0);
hThreadHandle = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)&ThreadActionFunction, NULL, 0, 0);
// action loop
int j = 0;
int w = 1;
do
{
j++;
Sleep(1000); //simul action
MyDebugOut(_T("main: will release thread j="), j);
// ReleaseMutex(hEventHandle_IxThr0M]); // thread should virtuel release shift key
if ( !SetEvent(hEventHandle) ) //release if shift key with hand
{
MyDebugOut(_T("main: SetEvent failure(2)! j="), j);
exit(-1);
}
} while (w);
MyDebugOut(_T("main: exit loop on j="), j);
return 0;
}
|