1

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.

deuberger
  • 3,578
  • 6
  • 31
  • 33
  • If already using Boost::Thread, why not also use Boost::asio to read? – Max Feb 09 '11 at 15:40
  • As far as I know, Boost.Asio won't solve my problem. I need to be able to determine whether the thread is currently blocking and interrupt it if it is. Boost.Asio would be useful in general, but doesn't solve this problem, right? – deuberger Feb 09 '11 at 16:04

2 Answers2

2

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).

caf
  • 233,326
  • 40
  • 323
  • 462
0

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.

Nils Pipenbrinck
  • 83,631
  • 31
  • 151
  • 221
  • Good points... thanks... are you saying there is no way to do this in Boost.Threads or that it can't be done in pthreads/NPTL either? I think that is the case, so I would have to revert to something even more low level, which I don't think I want to do. – deuberger Feb 09 '11 at 15:57