-
-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathSetTimeout.cpp
69 lines (61 loc) · 1.95 KB
/
SetTimeout.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include <mutex>
#include <thread>
#include "SetTimeout.h"
#include "Constants.h"
#ifdef WIN32
DWORD WINAPI TimeoutThreadExecutor(LPVOID lpParam) {
TimeoutData* threadData = (TimeoutData*)lpParam;
std::this_thread::sleep_for(std::chrono::milliseconds(threadData->timeout * 1000));
threadData->operation(threadData->data);
free(threadData);
return 0;
}
#endif
TimeoutOutputData setTimeout(int timeout, void * data, void(*operation)(void*)) {
std::thread::native_handle_type darwinHandle = nullptr;
HANDLE windowsHandle = nullptr;
struct TimeoutData* timeoutData = nullptr;
if (timeout > 0) {
timeoutData = reinterpret_cast<TimeoutData*>(malloc(sizeof(struct TimeoutData)));
timeoutData->timeout = timeout;
timeoutData->data = data;
timeoutData->operation = operation;
#ifdef WIN32
windowsHandle = CreateThread(
NULL, // default security attributes
0, // use default stack size
TimeoutThreadExecutor, // thread function name
timeoutData, // argument to thread function
0, // use default creation flags
nullptr);
#else
std::thread thread = std::thread([=]() {
std::this_thread::sleep_for(std::chrono::milliseconds(timeoutData->timeout * 1000));
timeoutData->operation(timeoutData->data);
});
darwinHandle = thread.native_handle();
thread.detach();
#endif
}
return { darwinHandle, windowsHandle, timeoutData };
}
void clearTimeout(TimeoutOutputData data) {
if (data.timeoutData) {
free(data.timeoutData);
data.timeoutData = nullptr;
}
#ifdef WIN32
if (data.windowsHandle) {
int terminateThreadResult = TerminateThread(data.windowsHandle, 9);
// https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-terminatethread#return-value
if (terminateThreadResult == 0)
{
DWORD errorCode = GetLastError();
}
}
#else
if (data.darwinHandle) {
pthread_cancel(data.darwinHandle);
}
#endif
}