c++ - Handling threads in server application after clients disconnect -


i'm working on simple http server. use winsock , standard threads c++11. each connected (accepted) client there new thread created.

std::map<socket, std::thread> threads;  bool server_running = true; while(server_running) {     socket client_socket;     client_socket = accept(listen_socket, null, null);     if(client_socket == invalid_socket) {         // error handling     }     threads[client_socket] = std::thread(clienthandler, client_socket); } 

clienthandler function looks this:

while(1) {     while(!all_data_received) {         bytes_received = recv(client_socket, recvbuf, recvbuflen, 0);         if(bytes_received > 0) {             //         } else {             goto client_cleanup;         }     }     // } client_cleanup: // here when connection: close received closesocket(client_socket); 

and here come problem - how handle threads ended haven't been joined main thread , references them still exist in threads map?

the simplest solution iterate on threads (e.q. thread?) , join , delete returned.

please share expertise. :)

ps. yes, know thread pool pattern. i'm not using in app (for better or worse). i'm looking answer concerning current architecture.

simple solution? detach() after start thread. mean once thread terminates resources cleaned , don't need keep std::map<socket, std::thread> threads.

std::thread(clienthandler, client_socket).detach(); 

otherwise create thread-safe lifo queue during cleanup push socket it.

then in main loop alternately check accept , queue , when queue has sockets in them threads.erase(socket); each socket in queue.

however if may putt lifo in other direction , use thread pool.


Comments