From dfb8bd8c95a5ff8633214f483f358d24071a7d8a Mon Sep 17 00:00:00 2001 From: rodri Date: Wed, 21 Jul 2021 20:08:58 +0000 Subject: implement a primitive VLA to keep connection state. --- dat.h | 8 ++++++++ muswd.c | 32 ++++++++++++++++++++++++++------ 2 files changed, 34 insertions(+), 6 deletions(-) diff --git a/dat.h b/dat.h index 97e0719..66db045 100644 --- a/dat.h +++ b/dat.h @@ -2,6 +2,7 @@ typedef struct GameState GameState; typedef struct Derivative Derivative; +typedef struct Conn Conn; struct GameState { @@ -12,3 +13,10 @@ struct Derivative { double dx, dv; }; + +struct Conn +{ + int *fds; + ulong off; + ulong cap; +}; diff --git a/muswd.c b/muswd.c index 4ebdb5e..c652b39 100644 --- a/muswd.c +++ b/muswd.c @@ -9,8 +9,7 @@ int debug; GameState state; double t, Δt; -int *conns; -int nconns; +Conn conns; static long _iolisten(va_list *arg) @@ -55,8 +54,15 @@ threadlisten(void *arg) continue; } - conns = erealloc(conns, ++nconns*sizeof(*conns)); - conns[nconns-1] = dfd; + if(conns.off >= conns.cap){ + conns.cap += 8; + conns.fds = erealloc(conns.fds, conns.cap*sizeof(*conns.fds)); + } + conns.fds[conns.off++] = dfd; + + if(debug) + fprint(2, "added conn %d for %lud conns at %lud max\n", + dfd, conns.off, conns.cap); } } @@ -89,8 +95,19 @@ threadsim(void *) then = now; timeacc += frametime/1e9; - for(i = 0; i < nconns; i++) - fprint(conns[i], "state: x=%g v=%g\n", state.x, state.v); + for(i = 0; i < conns.off; i++) + if(fprint(conns.fds[i], "state: x=%g v=%g\n", state.x, state.v) < 0){ + fprint(2, "client #%d hanged up\n", i+1); + if(conns.off < conns.cap-1) + memmove(&conns.fds[conns.off], &conns.fds[conns.off+1], conns.cap-conns.off - 1); + conns.off--; + + if(debug) + fprint(2, "removed conn %d for %lud conns at %lud max\n", + i, conns.off, conns.cap); + + i--; + } while(timeacc >= Δt){ integrate(&state, t, Δt); @@ -129,6 +146,9 @@ threadmain(int argc, char *argv[]) if(acfd < 0) sysfatal("announce: %r"); + conns.fds = emalloc(2*sizeof(*conns.fds)); + conns.cap = 2; + threadcreate(threadlisten, adir, 4096); threadcreate(threadsim, nil, 4096); threadexits(nil); -- cgit v1.2.3