-
Notifications
You must be signed in to change notification settings - Fork 13
/
async.c
77 lines (63 loc) · 1.71 KB
/
async.c
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
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <err.h>
#include <sys/epoll.h>
#include <sys/timerfd.h>
#include <dynamic.h>
struct state
{
core core;
pool pool;
int timer;
_Atomic size_t jobs;
};
static core_status async(core_event *event)
{
struct state *state = event->state;
if (event->type == POOL_REQUEST)
{
usleep(10000);
state->jobs++;
}
return CORE_OK;
}
core_status timeout(core_event *event)
{
struct state *state = event->state;
core_counters *counters;
uint64_t exp;
ssize_t n;
int i;
while (1)
{
n = read(state->timer, &exp, sizeof exp);
if (n == -1 && errno == EAGAIN)
break;
if (n != sizeof exp)
err(1, "read");
counters = core_get_counters(&state->core);
(void) printf("[timer %lu, jobs %lu]\n", exp, state->jobs);
(void) printf("[stats polls %lu, events %lu, awake %lu, total %lu, usage %f\n",
counters->polls, counters->events, counters->awake, counters->awake + counters->sleep,
(double) counters->awake / (double) (counters->awake + counters->sleep));
core_clear_counters(&state->core);
}
for (i = 0; i < 1000; i++)
pool_enqueue(&state->pool, async, state);
return CORE_OK;
}
int main()
{
struct state state = {0};
core_construct(&state.core);
pool_construct(&state.pool, &state.core);
pool_limits(&state.pool, 1, 32);
state.timer = timerfd_create(CLOCK_REALTIME, TFD_NONBLOCK | TFD_CLOEXEC);
timerfd_settime(state.timer, 0, (struct itimerspec[]) {{{1, 0}, {1, 0}}}, NULL);
core_add(&state.core, timeout, &state, state.timer, EPOLLIN | EPOLLET);
core_loop(&state.core);
close(state.timer);
pool_destruct(&state.pool);
core_destruct(&state.core);
}