diff options
-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); |