About using mg_ws_send on a separate thread #1449
-
Hello, first of all congratulation for the project, as a C lover this is the ONLY web server that really match what I like to code with! I have a pretty straightforward question: how safe it is to call Cheers |
Beta Was this translation helpful? Give feedback.
Replies: 5 comments 4 replies
-
@vb-mich , there are couple of things happen when you send data over the First, the data gets appended to the Another issue is that even if you add data, the IO thread does not know that the data was added - it may continue sleeping in The proper solution is to use the "pipe" connection - Now, let's assume you have a bunch of WS connections from multiple clients and you have some thread that wants to push to all of these connections from time to time. Here's how you do it: static void fn(struct mg_connection *c, int ev, void *ev_data, void *fn_data) {
...
}
// Pipe event handler. Called by the IO task
static void pcb(struct mg_connection *c, int ev, void *ev_data, void *fn_data) {
if (ev == MG_EV_READ) {
for (struct mg_connection *t = c->mgr->conns; t != NULL; t = t->next) {
if (t->label[0] == 'W') mg_ws_send(t, ....); // IMPORTANT: fn() must set the label on WS connections
}
}
}
static void my_task(struct mg_connection *c) {
...
mg_mgr_wakeup(c); // Something happened, wakeup mgr and let it call pcb handler
...
}
int main(int argc, char *argv[]) {
...
start_thread(my_task, mg_mkpipe(&mgr, pcb, NULL)); // Start another thread and pass a pipe connection as a param
mg_http_listen(&mgr, "http://localhost:8000", fn, &mgr); // Start listener which creates WS connections
for (;;) mg_mgr_poll(&mgr, 1000);
...
} |
Beta Was this translation helpful? Give feedback.
-
Good question.
We can make |
Beta Was this translation helpful? Give feedback.
-
Hi, As Thank you! |
Beta Was this translation helpful? Give feedback.
-
@t123yh are you using an RTOS or writing a bare metal firmware ? |
Beta Was this translation helpful? Give feedback.
-
|
Beta Was this translation helpful? Give feedback.
@vb-mich , there are couple of things happen when you send data over the
struct mg_connection *c
pointer.First, the data gets appended to the
c->send
buffer. Note, it is not gets send, it gets appended. So the first issue is to make sure no other thread deals with the send buffer. And you can't guarantee that, because the IO thread can send some remaining data and modify thec->send
whilst your thread adding some stuff to it.Another issue is that even if you add data, the IO thread does not know that the data was added - it may continue sleeping in
mg_poll()
. So your data gets sent whenever the main IO thread wakes up fromselect()
, and that depends on the polling interval you've set inm…