Skip to content

Commit

Permalink
async example
Browse files Browse the repository at this point in the history
  • Loading branch information
Fredrik Widlund committed Jan 8, 2020
1 parent 2feb7bc commit ed505c5
Show file tree
Hide file tree
Showing 2 changed files with 86 additions and 10 deletions.
17 changes: 7 additions & 10 deletions examples/Makefile.am
Original file line number Diff line number Diff line change
Expand Up @@ -5,21 +5,18 @@ AM_CXXFLAGS = -std=gnu++11
AM_CPPFLAGS = $(COMMON_FLAGS)
AM_LDFLAGS = $(COMMON_FLAGS)

bin_PROGRAMS = maps mapi list

maps_SOURCES = \
maps.c
bin_PROGRAMS = maps mapi list async

maps_SOURCES = maps.c
maps_LDADD = ../libdynamic.la

mapi_SOURCES = \
mapi.c

mapi_SOURCES = mapi.c
mapi_LDADD = ../libdynamic.la

list_SOURCES = \
list.c

list_SOURCES = list.c
list_LDADD = ../libdynamic.la

async_SOURCES = async.c
async_LDADD = ../libdynamic.la

MAINTAINERCLEANFILES = Makefile.in
79 changes: 79 additions & 0 deletions examples/async.c
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);
}

0 comments on commit ed505c5

Please sign in to comment.