Skip to content

Commit 30738f6

Browse files
authored
Merge pull request #2493 from cesanta/wake
Fix #2456 - wake up mongoose thread
2 parents bd53e46 + 122115d commit 30738f6

File tree

1 file changed

+22
-3
lines changed

1 file changed

+22
-3
lines changed

examples/multi-threaded/main.c

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,11 +10,18 @@
1010

1111
#include "mongoose.h"
1212

13+
#define LISTENING_ADDR "http://localhost:8000"
14+
1315
struct thread_data {
1416
struct mg_queue queue; // Worker -> Connection queue
1517
struct mg_str body; // Copy of message body
1618
};
1719

20+
// These two helper UDP connections are used to wake up mongoose thread
21+
static struct mg_connection *s_wakeup_server;
22+
static struct mg_connection *s_wakeup_client;
23+
#define WAKEUP_URL "udp://127.0.0.1:40111"
24+
1825
static void start_thread(void *(*f)(void *), void *p) {
1926
#ifdef _WIN32
2027
#define usleep(x) Sleep((x) / 1000)
@@ -46,13 +53,23 @@ static void *worker_thread(void *param) {
4653
free((char *) d->body.ptr);
4754
}
4855

56+
// Wake up Mongoose thread by sending something to one of its connections
57+
mg_send(s_wakeup_client, "hi", 2);
58+
4959
// Wait until connection reads our message, then it is safe to quit
5060
while (d->queue.tail != d->queue.head) usleep(1000);
5161
MG_INFO(("done, cleaning up..."));
5262
free(d);
5363
return NULL;
5464
}
5565

66+
static void wfn(struct mg_connection *c, int ev, void *ev_data, void *fn_data) {
67+
if (ev == MG_EV_READ) {
68+
c->recv.len = 0; // Discard received data
69+
}
70+
(void) ev_data, (void) fn_data;
71+
}
72+
5673
// HTTP request callback
5774
static void fn(struct mg_connection *c, int ev, void *ev_data, void *fn_data) {
5875
if (ev == MG_EV_HTTP_MSG) {
@@ -82,8 +99,10 @@ int main(void) {
8299
struct mg_mgr mgr;
83100
mg_mgr_init(&mgr);
84101
mg_log_set(MG_LL_DEBUG); // Set debug log level
85-
mg_http_listen(&mgr, "http://localhost:8000", fn, NULL); // Create listener
86-
for (;;) mg_mgr_poll(&mgr, 10); // Event loop. Use 10ms poll interval
87-
mg_mgr_free(&mgr); // Cleanup
102+
mg_http_listen(&mgr, LISTENING_ADDR, fn, NULL);
103+
s_wakeup_server = mg_listen(&mgr, WAKEUP_URL, wfn, NULL);
104+
s_wakeup_client = mg_connect(&mgr, WAKEUP_URL, wfn, NULL);
105+
for (;;) mg_mgr_poll(&mgr, 5000); // Event loop. Use 5s poll interval
106+
mg_mgr_free(&mgr); // Cleanup
88107
return 0;
89108
}

0 commit comments

Comments
 (0)