判断线程是否被阻塞
有谁知道如何确定线程当前是否阻塞?基本上,我想检查某个线程是否正在阻塞(在本例中是在 AF_UNIX 数据报套接字接收调用上),如果是,则向其发送信号以中断。
我正在使用 Boost.Thread 在 Linux 上工作,这意味着我正在使用 pthreads。我的系统有 NPTL。
我认为答案是“不”,但想看看我是否遗漏了一些东西。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这并不容易实现(可以使用针对调试器的功能,但它既不简单、可移植也不安全)。
无论如何,您实际上并不想这样做,因为这样的使用会产生固有的竞争条件。您可以在线程即将阻塞之前检查线程是否正在阻塞(在这种情况下,您将错过唤醒它的机会),或者在您发现它正在阻塞之后它可能会停止阻塞。
解决问题的常用方法是“自管道技巧”:
pipe()
创建管道;recvfrom()
中阻塞,而是在poll()
或select()
中阻塞。要监视的文件描述符包括数据报套接字和管道的读取端。(
recvfrom()
也应该更改为使用MSG_DONTWAIT
标志,因为我们不想在这里阻塞,并且总是在poll()
中阻塞代码> / <代码>select() 代替)。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":
pipe()
;recvfrom()
, blocks inpoll()
orselect()
. The file descriptors to monitor include the datagram socket and the read end of the pipe.(The
recvfrom()
should also be changed to use theMSG_DONTWAIT
flag, since we never want to block here, and always block in thepoll()
/select()
instead).答案是否定的。可能有一种方法可以在您的平台上执行此操作,但一般来说我不知道有什么方法可以执行此操作。
现在,在深入了解平台的较低级别文档之前,请三思是否这确实是您想要的:
线程总是由于某种原因而被阻塞。例如,它可能在 FILE IO 中被阻塞。如果正确处理返回值,则可以安全地中断此过程。另一方面,线程也可能在 new/delete 调用或另一个标准库函数中被阻塞。中断运行时库中的线程将导致灾难。
我知道你有理由在这里问,但恕我直言,最好从更高层次的角度思考你的问题,并以一种无需此类黑客就能达到目标的方式修复你的设计。
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.