How to cleanly interrupt a thread blocking on a recv call?

前端 未结 3 886
我在风中等你
我在风中等你 2021-01-02 06:51

I have a multithreaded server written in C, with each client thread looking something like this:

ssize_t n;
struct request request;

// Main loop: receive re         


        
3条回答
  •  有刺的猬
    2021-01-02 07:37

    So you have at least these possibilities:

    (1) pthread_kill will blow the thread out of recv with errno == EINTR and you can clean up and exit the thread on your own. Some people think this is nasty. Depends, really.

    (2) Make your client socket(s) non-blocking and use select to wait on input for a specific period of time before checking if a switch used between the threads has been set to indicated they should shut down.

    (3) In combo with (2) have each thread share a pipe with the master thread. Add it to the select. If it becomes readable and contains a shutdonw request, the thread shuts itself down.

    (4) Look into the pthread_cancel mechanism if none of the above (or variations thereof) do not meet your needs.

提交回复
热议问题