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
|
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <stdio.h>
#include <conio.h>
#include <process.h>
const char* const ev1 = "thterm";
const char* const ev2 = "thstrt";
unsigned __stdcall myThread(LPVOID) {
const HANDLE hterm = OpenEvent(EVENT_ALL_ACCESS, FALSE, ev1);
const HANDLE hstart = OpenEvent(EVENT_ALL_ACCESS, FALSE, ev2);
if (hterm == 0 || hstart == 0) {
puts("Cannot open events");
return 1;
}
SetEvent(hstart);
SuspendThread(GetCurrentThread());
const char* const str = "abcdefghijklmnopqrstuvwxyz";
for (unsigned i = 0; WaitForSingleObject(hterm, 1000) == WAIT_TIMEOUT; )
putchar(str[i++ % 26]);
return 0;
}
int main() {
const HANDLE hterm = CreateEvent(NULL, TRUE, FALSE, ev1);
const HANDLE hstart = CreateEvent(NULL, TRUE, FALSE, ev2);
const HANDLE hthrd = (HANDLE)_beginthreadex(NULL, NULL, &myThread, NULL, 0, NULL);
if (hthrd == 0) {
puts("Failed to start thread");
return 1;
}
DWORD ecode = 99;
if (WaitForSingleObject(hstart, 1000) == WAIT_OBJECT_0) {
puts("Thread started ok - suspended\n(s)uspend, (r)resume, (t)terminate: ");
while (WaitForSingleObject(hthrd, 0)) {
if (_kbhit())
switch (_getch()) {
case 's':
SuspendThread(hthrd);
break;
case 'r':
ResumeThread(hthrd);
break;
case 't':
ResumeThread(hthrd);
SetEvent(hterm);
break;
default:
putchar('\a');
break;
}
}
} else
puts("Thread not running!");
GetExitCodeThread(hthrd, &ecode);
if (ecode)
printf("Issue with thread - %u\n", ecode);
else
puts("\nThread terminated OK");
return ecode;
}
| |