breaking out from socket select

前端 未结 4 1874
暖寄归人
暖寄归人 2020-12-04 02:00

I have a loop which basically calls this every few seconds (after the timeout):

 while(true){

    if(finished)
       return;

    switch(select(FD_SETSIZE,         


        
相关标签:
4条回答
  • 2020-12-04 02:11

    Can't you just make the timeout sufficiently short (like 10ms or so?).

    These "just create a dummy connection"-type solution seem sort of hacked. I personally think that if an application is well designed, concurrent tasks never have to be interrupted forcefully, the just has worker check often enough (this is also a reason why boost.threads do not have a terminate function).

    Edit Made this answer CV. It is bad, but it might help other to understand why it is bad, which is explained in the comments.

    0 讨论(0)
  • 2020-12-04 02:15

    The easiest way is probably to use pipe(2) to create a pipe and add the read end to readfds. When the other thread wants to interrupt the select() just write a byte to it, then consume it afterward.

    0 讨论(0)
  • 2020-12-04 02:18

    You can use shutdown(Sock, SHUT_RDWR) call from main thread to come out of waiting select call which will also exit your another thread before the timeout so you don't need to wait till timeout expires.

    cheers. :)

    0 讨论(0)
  • 2020-12-04 02:24

    Yes, you create a connected pair of sockets. Then thread B writes to one side of socket and thread A adds the other side socket to select. So once B writes to socket A exits select, do not forget to read this byte from socket.

    This is the most standard and common way to interrupt selects.

    Notes:

    Under Unix, use socketpair to create a pair of sockets, under windows it is little bit tricky but googling for Windows socketpair would give you samples of code.

    0 讨论(0)
提交回复
热议问题