ref: dfb8bd8c95a5ff8633214f483f358d24071a7d8a
parent: 10f8e5542686760b772abf40929a51fb63afad93
author: rodri <rgl@antares-labs.eu>
date: Wed Jul 21 16:08:58 EDT 2021
implement a primitive VLA to keep connection state.
--- a/dat.h
+++ b/dat.h
@@ -2,6 +2,7 @@
typedef struct GameState GameState;
typedef struct Derivative Derivative;
+typedef struct Conn Conn;
struct GameState
{
@@ -11,4 +12,11 @@
struct Derivative
{
double dx, dv;
+};
+
+struct Conn
+{
+ int *fds;
+ ulong off;
+ ulong cap;
};
--- a/muswd.c
+++ b/muswd.c
@@ -9,8 +9,7 @@
GameState state;
double t, Δt;
-int *conns;
-int nconns;
+Conn conns;
static long
_iolisten(va_list *arg)
@@ -55,8 +54,15 @@
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,9 +95,20 @@
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);
timeacc -= Δt;
@@ -128,6 +145,9 @@
acfd = announce("tcp!*!112", adir);
if(acfd < 0)
sysfatal("announce: %r");
+
+ conns.fds = emalloc(2*sizeof(*conns.fds));
+ conns.cap = 2;
threadcreate(threadlisten, adir, 4096);
threadcreate(threadsim, nil, 4096);