forked from luncliff/coroutine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwindows_on_apc_known.cpp
53 lines (43 loc) · 1.52 KB
/
windows_on_apc_known.cpp
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
/**
* @author github.com/luncliff (luncliff@gmail.com)
*/
#undef NDEBUG
#include <atomic>
#include <cassert>
#include <iostream>
#include <gsl/gsl>
#include <coroutine/return.h>
#include <coroutine/windows.h>
using namespace std;
using namespace coro;
auto procedure_call_on_known_thread(HANDLE thread, HANDLE event) -> frame_t {
co_await continue_on_apc{thread};
if (SetEvent(event) == FALSE)
cerr << system_category().message(GetLastError()) << endl;
}
DWORD WINAPI wait_in_sleep(LPVOID) {
SleepEx(1000, true);
return GetLastError();
}
int main(int, char*[]) {
HANDLE event = CreateEvent(nullptr, false, false, nullptr);
assert(event != INVALID_HANDLE_VALUE);
auto on_return_1 = gsl::finally([event]() { CloseHandle(event); });
DWORD worker_id{};
HANDLE worker = CreateThread(nullptr, 0, //
wait_in_sleep, nullptr, 0, &worker_id);
assert(worker != 0);
auto on_return_2 = gsl::finally([worker]() { CloseHandle(worker); });
SleepEx(500, true);
procedure_call_on_known_thread(worker, event);
HANDLE handles[2] = {event, worker};
auto ec = WaitForMultipleObjectsEx(2, handles, TRUE, INFINITE, true);
// expect the wait is cancelled by APC (WAIT_IO_COMPLETION)
assert(ec == WAIT_OBJECT_0 || ec == WAIT_IO_COMPLETION);
DWORD retcode{};
GetExitCodeThread(worker, &retcode);
// we used QueueUserAPC so the return can be 'elapsed' milliseconds
// allow zero for the timeout
assert(retcode >= 0);
return EXIT_SUCCESS;
}