@@ -63,6 +63,8 @@ static int new_udp_listen_socket(void);
6363static void safer_shutdown (thread_args_t * args );
6464static void * server_work (void * thread_args );
6565static void sig_handler (const int sig );
66+ static void cleanup_threadpool (pthread_t * threads , thread_args_t * args ,
67+ int n_threads );
6668
6769int
6870main (int argc ,
@@ -224,25 +226,19 @@ main(int argc,
224226 }
225227 }
226228
227- #ifdef USE_NONBLOCK_JOIN
228- for (size_t i = 0 ; i < n_threads ; ++ i ) {
229- if (threads [i ]) {
230- pthread_tryjoin_np (threads [i ], NULL );
231- printf ("info: joined thread: %ld\n" , threads [i ]);
232- threads [i ] = 0 ;
233- }
234- }
235- #else
236- for (size_t i = 0 ; i < n_threads ; ++ i ) {
237- if (threads [i ] && args [i ].done == 1 ) {
238- pthread_join (threads [i ], NULL );
239- printf ("info: joined thread: %ld\n" , threads [i ]);
240- threads [i ] = 0 ;
241- }
229+ cleanup_threadpool (threads , args , n_threads );
230+ }
231+
232+ /* Do a final blocking join. */
233+ for (size_t i = 0 ; i < n_threads ; ++ i ) {
234+ if (threads [i ]) {
235+ pthread_join (threads [i ], NULL );
236+ printf ("info: joined thread: %ld\n" , threads [i ]);
237+ threads [i ] = 0 ;
242238 }
243- #endif
244239 }
245240
241+ /* All threads exited. Do a final cleanup pass just in case. */
246242 for (size_t i = 0 ; i < n_threads ; ++ i ) {
247243 safer_shutdown (& args [i ]);
248244 }
@@ -398,3 +394,29 @@ sig_handler(const int sig)
398394 stop_server = 1 ;
399395 return ;
400396}
397+
398+ static void
399+ cleanup_threadpool (pthread_t * threads ,
400+ thread_args_t * args ,
401+ int n_threads )
402+ {
403+ #ifdef USE_NONBLOCK_JOIN
404+ for (size_t i = 0 ; i < n_threads ; ++ i ) {
405+ if (threads [i ]) {
406+ pthread_tryjoin_np (threads [i ], NULL );
407+ printf ("info: joined thread: %ld\n" , threads [i ]);
408+ threads [i ] = 0 ;
409+ }
410+ }
411+ #else
412+ for (size_t i = 0 ; i < n_threads ; ++ i ) {
413+ if (threads [i ] && args [i ].done == 1 ) {
414+ pthread_join (threads [i ], NULL );
415+ printf ("info: joined thread: %ld\n" , threads [i ]);
416+ threads [i ] = 0 ;
417+ }
418+ }
419+ #endif
420+
421+ return ;
422+ }
0 commit comments