diff options
author | rodri <rgl@antares-labs.eu> | 2021-07-21 20:08:58 +0000 |
---|---|---|
committer | rodri <rgl@antares-labs.eu> | 2021-07-21 20:08:58 +0000 |
commit | dfb8bd8c95a5ff8633214f483f358d24071a7d8a (patch) | |
tree | 2ce57d0749d6d6a29aa903e89901e277ef1f7004 | |
parent | 10f8e5542686760b772abf40929a51fb63afad93 (diff) | |
download | musw-dfb8bd8c95a5ff8633214f483f358d24071a7d8a.tar.gz musw-dfb8bd8c95a5ff8633214f483f358d24071a7d8a.tar.bz2 musw-dfb8bd8c95a5ff8633214f483f358d24071a7d8a.zip |
implement a primitive VLA to keep connection state.
-rw-r--r-- | dat.h | 8 | ||||
-rw-r--r-- | muswd.c | 32 |
2 files changed, 34 insertions, 6 deletions
@@ -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; +}; @@ -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); |