|
10 | 10 |
|
11 | 11 | #include "mongoose.h" |
12 | 12 |
|
| 13 | +#define LISTENING_ADDR "http://localhost:8000" |
| 14 | + |
13 | 15 | struct thread_data { |
14 | 16 | struct mg_queue queue; // Worker -> Connection queue |
15 | 17 | struct mg_str body; // Copy of message body |
16 | 18 | }; |
17 | 19 |
|
| 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 | + |
18 | 25 | static void start_thread(void *(*f)(void *), void *p) { |
19 | 26 | #ifdef _WIN32 |
20 | 27 | #define usleep(x) Sleep((x) / 1000) |
@@ -46,13 +53,23 @@ static void *worker_thread(void *param) { |
46 | 53 | free((char *) d->body.ptr); |
47 | 54 | } |
48 | 55 |
|
| 56 | + // Wake up Mongoose thread by sending something to one of its connections |
| 57 | + mg_send(s_wakeup_client, "hi", 2); |
| 58 | + |
49 | 59 | // Wait until connection reads our message, then it is safe to quit |
50 | 60 | while (d->queue.tail != d->queue.head) usleep(1000); |
51 | 61 | MG_INFO(("done, cleaning up...")); |
52 | 62 | free(d); |
53 | 63 | return NULL; |
54 | 64 | } |
55 | 65 |
|
| 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 | + |
56 | 73 | // HTTP request callback |
57 | 74 | static void fn(struct mg_connection *c, int ev, void *ev_data, void *fn_data) { |
58 | 75 | if (ev == MG_EV_HTTP_MSG) { |
@@ -82,8 +99,10 @@ int main(void) { |
82 | 99 | struct mg_mgr mgr; |
83 | 100 | mg_mgr_init(&mgr); |
84 | 101 | 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 |
88 | 107 | return 0; |
89 | 108 | } |
0 commit comments