开发者

Thread blocked waiting message

开发者 https://www.devze.com 2023-02-28 09:26 出处:网络
I have a pthread running and waiting for messages from a socket. The thread gets blocked to wait a message and doesn\'t wake up until receiving a new one. Is there a way to send a signal to thread to

I have a pthread running and waiting for messages from a socket. The thread gets blocked to wait a message and doesn't wake up until receiving a new one. Is there a way to send a signal to thread to wake up and for the receive function (recvmsg) to return an error code related to开发者_StackOverflow中文版 signal?


Yes, by default SIGINT will interrupt all syscalls. From man recv:

    EINTR  The receive was interrupted by delivery of a signal before any 
           data were available; see signal(7). 
and 
    MSG_WAITALL (since Linux 2.2)
          This flag requests that the operation block until the full request is 
          satisfied.  However, the call may still return less data than requested
          if a signal is caught, an error or disconnect occurs, or the next 
          data to be received is of a different type than that returned.

However, you cannot target a specific thread or specific operation.

If you wish to have this, I suggest using a condition that the receiving thread can explicitely listen for. There is a wellknown trick on linux which allows the receiving thread to use select or poll to listen for the socket and the 'condition' simultaneously[1].

The trick is to open a pipe from the master thread to the client (receiving) thread. The master writes to the pipe upon reaching a certain state (the signal so to speak). The client (receiving) thread can simply poll both the pipe and the socket and only check which of the two awoke it.


[1] normally pthread_cond_wait and poll/select cannot be combined without racing so you'd need to program wait loops with small timeouts. On Win32 by contrast it is as simple as WaitForMultipleObjects and you're done

0

精彩评论

暂无评论...
验证码 换一张
取 消