I am learning Pthreads, and was wondering what is the best way to kill such an object. After looking for similar questions I was not able to find a "clear" answer but please feel free to point me to any relevant questions.
I am working with a small client server application, where the server main's thread is listening on a socket for clients connections. Each time a client connects, the server create a new thread performing "infinite works" in a while true loop. Now I want to stop this loop when the same client send a "stop" request on the socket.
How would you implement such a behavior knowing that clients are identified through an ID provided within each socket messages ? Using a shared variable (between main server thread and client server threads) as a tes condition in the while loop. Using a PThread function ?
You shouldn't force the thread to exit. You should design your program such that the while loop exists when "stop" is sent.
Something like:
You can design your server like this:
There is no way to forcibly kill a single POSIX thread; this is intentional, by design. Instead, if your thread needs to be stoppable by other threads, you should design the code that runs in it to take this into account. The idiomatic way to do this is with an exit flag variable (protected by a mutex) and a condition variable.
There is also
pthread_cancel
, which can be used to request that a thread exit. Using it correctly requires setting up cleanup handlers withpthread_cleanup_push
and/or disabling cancellation temporarily withpthread_setcancelstate
.