-
Notifications
You must be signed in to change notification settings - Fork 2
/
timer.hpp
59 lines (54 loc) · 1.77 KB
/
timer.hpp
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
#include <time.h>
#include <pthread.h>
#include <stdint.h>
class timer
{
struct waitThenCallArguments
{
uint32_t toWait;
void (*callbackFunction)(void*);
void* arguments;
};
static void waitMilliseconds(uint32_t toWait)
{
struct timespec ts;
ts.tv_sec = toWait / 1000;
ts.tv_nsec = (toWait % 1000) * 1000000;
nanosleep(&ts, &ts);
}
static void* waitThenCall(void* arguments)
{
waitThenCallArguments* args = (waitThenCallArguments*)arguments;
waitMilliseconds(args->toWait);
args->callbackFunction(args->arguments);
return NULL;
}
static void* waitThenCallRepeat(void* arguments)
{
while(true)
{
waitThenCall(arguments);
}
}
public:
static pthread_t asyncTimer(uint32_t toWait, void (*callbackFunction)(void*), void* arguments)
{
waitThenCallArguments* argumentsToPass = (waitThenCallArguments*)malloc(sizeof(waitThenCallArguments));
argumentsToPass->callbackFunction = callbackFunction;
argumentsToPass->toWait = toWait;
argumentsToPass->arguments = arguments;
pthread_t thread;
pthread_create(&thread, NULL, waitThenCall, argumentsToPass);
return thread;
}
static pthread_t asyncTimerRepeat(uint32_t toWait, void (*callbackFunction)(void*), void* arguments)
{
waitThenCallArguments* argumentsToPass = (waitThenCallArguments*)malloc(sizeof(waitThenCallArguments));
argumentsToPass->callbackFunction = callbackFunction;
argumentsToPass->toWait = toWait;
argumentsToPass->arguments = arguments;
pthread_t thread;
pthread_create(&thread, NULL, waitThenCallRepeat, argumentsToPass);
return thread;
}
};