-
Notifications
You must be signed in to change notification settings - Fork 13
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Fredrik Widlund
committed
Jan 8, 2020
1 parent
2feb7bc
commit ed505c5
Showing
2 changed files
with
86 additions
and
10 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,79 @@ | ||
#include <stdio.h> | ||
#include <stdint.h> | ||
#include <stdlib.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; | ||
}; | ||
|
||
void async(void *state) | ||
{ | ||
usleep(10000); | ||
((struct state *) state)->jobs ++; | ||
} | ||
|
||
core_status collect(core_event *event) | ||
{ | ||
struct state *state = event->state; | ||
void *result; | ||
|
||
do | ||
result = pool_collect(&state->pool, POOL_DONTWAIT); | ||
while (result); | ||
|
||
return CORE_OK; | ||
} | ||
|
||
core_status timeout(core_event *event) | ||
{ | ||
struct state *state = event->state; | ||
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"); | ||
|
||
(void) printf("[timer %lu, jobs %lu]\n", exp, state->jobs); | ||
} | ||
|
||
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.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_add(&state.core, collect, &state, pool_fd(&state.pool), EPOLLIN | EPOLLET); | ||
|
||
core_loop(&state.core); | ||
|
||
close(state.timer); | ||
pool_destruct(&state.pool); | ||
core_destruct(&state.core); | ||
} |