1 Attachment(s)
Re: thread synchronisation
Here you can find a very basic sample for threads interaction. Please ask any questions you have about it.
Code:
#include <windows.h>
#include <stdio.h>
#include <conio.h>
#include <tchar.h>
HANDLE hPrintEvent = NULL;
HANDLE hStopEvent = NULL;
const DWORD PRINT_TIMEOUT = 200; // milliseconds, the main print interval
DWORD WINAPI ThreadProc(LPVOID pVoid)
{
__int64 counter = 0;
_tprintf(TEXT("\n> "));
while (1)
{
DWORD waitRes = WaitForSingleObject(hStopEvent, PRINT_TIMEOUT);
switch (waitRes)
{
case WAIT_ABANDONED:
case WAIT_FAILED:
_tprintf(TEXT("\nWaiting failed. Quit.\n"));
return 0;
case WAIT_OBJECT_0:
_tprintf(TEXT("\nStop signal caught. Quit.\n"));
return 0;
case WAIT_TIMEOUT:
waitRes = WaitForSingleObject(hPrintEvent, 0);
if (WAIT_OBJECT_0 == waitRes)
{
// print allowed
++counter;
_tprintf(TEXT("\r \r> %I64d"), counter);
}
break;
}
}
return 0;
}
int _tmain()
{
hPrintEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
hStopEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
DWORD threadId;
HANDLE hThread = CreateThread(NULL, 0, ThreadProc, NULL, 0, &threadId);
if (hThread)
{
_tprintf(TEXT("Press p to resume printing, s to suspend it, and q to quit.\n> "));
while (1)
{
int ch = getch();
if ('p' == ch)
SetEvent(hPrintEvent);
else if ('s' == ch)
ResetEvent(hPrintEvent);
else if ('q' == ch)
{
SetEvent(hStopEvent);
break;
}
}
WaitForSingleObject(hThread, INFINITE);
}
CloseHandle(hPrintEvent);
CloseHandle(hStopEvent);
CloseHandle(hThread);
return 0;
}