#include <iostream>
#include <windows.h>
#include <process.h>
#include <conio.h>
enum {
EVT_PAUSE = 0,
EVT_RESUME,
EVT_QUIT,
EVT_TOTAL
};
static HANDLE events[EVT_TOTAL] = { NULL,NULL,NULL };
static unsigned int __stdcall helper_thread_proc(void * para)
{
int key;
bool quit = false;
do {
key = _getch();
switch (key) {
case 'q':
case 'Q':
SetEvent(events[EVT_PAUSE]);
break;
case 'w':
case 'W':
SetEvent(events[EVT_RESUME]);
break;
case 'e':
case 'E':
quit = true;
SetEvent(events[EVT_QUIT]);
break;
default:
break;
}
if(quit)
break;
} while (1);
return 0;
}
static HANDLE start_helper_thread()
{
HANDLE hdl;
hdl = (HANDLE)_beginthreadex(NULL, 0, helper_thread_proc, NULL, 0, NULL);
return hdl;
}
static unsigned int _stdcall result_monitor_thread(void* para)
{
unsigned int i = 1;
while (1)
{
std::cout << i << std::endl;
++i;
}
return 0;
}
static HANDLE start_monitor_thread()
{
HANDLE hdl;
hdl = (HANDLE)_beginthreadex(NULL, 0, result_monitor_thread, NULL, 0, NULL);
return hdl;
}
int main()
{
HANDLE hdl = start_monitor_thread();
if (hdl == NULL) {
printf("create monitor thread failed\n");
}
HANDLE helper_thread = start_helper_thread();
if (helper_thread == NULL) {
printf("create helper thread failed\n");
}
DWORD waitres;
for (int i = 0; i < EVT_TOTAL; ++i) {
events[i] = CreateEvent(NULL, FALSE, FALSE, NULL);
}
bool quit = false;
while(1)
{
waitres = WaitForMultipleObjects(EVT_TOTAL, events, FALSE, INFINITE);
switch (waitres)
{
case WAIT_OBJECT_0 + EVT_PAUSE:
SuspendThread(hdl);
break;
case WAIT_OBJECT_0 + EVT_RESUME:
ResumeThread(hdl);
break;
case WAIT_OBJECT_0 + EVT_QUIT:
quit = true;
break;
default:
break;
}
if (quit)
break;
}
if (hdl != NULL)
{
CloseHandle(hdl);
}
if (helper_thread != NULL) {
WaitForSingleObject(helper_thread, INFINITE);
CloseHandle(helper_thread);
}
return 0;
}