@@ -24,11 +24,23 @@ static void start_thread(void (*f)(void *), void *p) {
2424#endif
2525}
2626
27+ struct userdata {
28+ int sock ; // Paired socket, worker thread owns it
29+ struct mg_str
30+ body ; // data to be processed
31+ };
32+
2733static void thread_function (void * param ) {
28- int sock = (int ) (size_t ) param ; // Paired socket. We own it
29- sleep (2 ); // Simulate long execution
30- send (sock , "hi" , 2 , 0 ); // Wakeup event manager
31- close (sock ); // Close the connection
34+ struct userdata * p = (struct userdata * ) param ;
35+ sleep (2 ); // Simulate long execution
36+ // Respond, wakeup event manager
37+ if (p -> body .len )
38+ send (p -> sock , p -> body .ptr , p -> body .len , 0 ); // if there is a body, echo it
39+ else
40+ send (p -> sock , "hi" , 2 , 0 ); // otherwise just respond "hi"
41+ close (p -> sock ); // Close the connection
42+ free ((void * ) p -> body .ptr ); // free body
43+ free (p ); // free userdata
3244}
3345
3446static void link_conns (struct mg_connection * c1 , struct mg_connection * c2 ) {
@@ -67,8 +79,12 @@ static void fn(struct mg_connection *c, int ev, void *ev_data, void *fn_data) {
6779 mg_http_reply (c , 200 , "Host: foo.com\r\n" , "hi\n" );
6880 } else {
6981 // Multithreading code path
70- int sock = mg_mkpipe (c -> mgr , pcb , c , true); // Create pipe
71- start_thread (thread_function , (void * ) (size_t ) sock ); // Start thread
82+ struct userdata * data = calloc (1 , sizeof (* data )); // worker will free it
83+ // parse headers or use request body, duplicate data and pass it to worker
84+ // thread
85+ data -> body = mg_strdup (hm -> body ); // worker will free it
86+ data -> sock = mg_mkpipe (c -> mgr , pcb , c , true); // Create pipe
87+ start_thread (thread_function , data ); // Start thread and pass data
7288 }
7389 } else if (ev == MG_EV_CLOSE ) {
7490 if (c -> fn_data != NULL ) unlink_conns (c , c -> fn_data );
0 commit comments