Determine whether a thread is blocked

3.9k views Asked by At

Does anyone know of a way to determine whether a thread is currently blocking? Basically, I want to check whether a certain thread is blocking (in this case on a AF_UNIX datagram socket receive call) and send it a signal to interrupt if it is.

I'm working on Linux using Boost.Thread meaning underneath I'm using pthreads. My system has NPTL.

I think the answer is "no", but want to see if I'm missing something.

2

There are 2 answers

0
caf On BEST ANSWER

This is not easily possible (it is possible using the functionality that is intended for debuggers, but it is neither simple, portable or safe).

You do not really want to do this anyway, because such a use would have an inherent race condition. You may check if the thread is blocking just before it is about to block (in which case you would miss waking it), or it may stop blocking just after you find that it is blocking.

The usual method to solve your problem is the "self-pipe trick":

  • Create a pipe with pipe();
  • The target thread, instead of blocking in recvfrom(), blocks in poll() or select(). The file descriptors to monitor include the datagram socket and the read end of the pipe.
  • To wake up the target thread, the other thread writes a single byte to the write end of the pipe.

(The recvfrom() should also be changed to use the MSG_DONTWAIT flag, since we never want to block here, and always block in the poll() / select() instead).

1
Nils Pipenbrinck On

The answer is no. There might be a way to do this on your platform, but in general I know of no way to do this.

Now, before you dive into the lower level documentation of your platform think twice if this is really what you want:

A thread is always blocked for a reason. For example it may be blocked in FILE IO. This could be interrupted safely if you handle the return values correctly. On the other hand the thread may also be blocked within a new/delete call or another standard library function. Interrupting a thread within the runtime library is a receipt for a disaster.

I know you have a reason to ask here, but imho it is better think about your problem from a higher-level perspective and fix your design in a way that you can reach your goal without such hacks.