pthread_kill()vs pthread_cancel()终止为I/O阻塞的线程 [英] pthread_kill() vs pthread_cancel() to terminate a thread blocked for I/O

查看:76
本文介绍了pthread_kill()vs pthread_cancel()终止为I/O阻塞的线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我们的服务器代码中,我们使用poll()系统调用来监视客户端套接字.使用较大的超时值调用poll().因此,调用poll()的线程将被阻止进行I/O.

In our server code we are using poll() system call for monitoring client sockets. The poll() is called with a large timeout value. So the thread calling poll() gets blocked for I/O.

按照流程,我们有一个场景,我们需要终止来自另一个线程的poll()中阻塞的线程.我遇到过pthread_kill()和pthread_cancel()函数,它们可以终止为I/O阻塞的目标线程.

As per the flow, we have a scenario where we need to terminate thread that blocked in poll() from a different thread. I have came across pthread_kill() and pthread_cancel() functions, which can terminate the target thread blocked for I/O.

通过阅读手册页,这两个功能似乎都能正常工作.互联网上很少有链接表明这两种功能都使用起来很危险.

By reading the man pages, both these functions seems to work fine. Few links on internet suggested that both of these functions are dangerous to use.

是否有其他方法可以终止为I/O阻塞的线程?如果没有,建议使用以下哪个功能.

Is there any alternative way to terminate the thread blocked for I/O ? If not, which of these functions is recommended to use.

推荐答案

一个简单干净的方法是创建信号"管道.也就是说,调用 pipe ,获取"read"端的文件描述符,并将其添加到 pol 文件描述符列表中(使用 POLLIN ).然后,每当您要解除阻塞在 poll 中等待的线程时,只需将一个字节写入管道的写入端即可.接收到数据的管道将在阻塞线程中以可读形式返回.您甚至可以通过更改写入的字节值来指定不同的命令".

An easy and clean option is to create a "signal" pipe. That is, call pipe, take the file descriptor for the "read" end and add it to your list of poll file descriptors (with POLLIN). Then, whenever you want to unblock the thread which is waiting in poll, just write a byte to the write end of the pipe. The pipe, having received data, will return as readable in the blocked thread. You can even specify different "commands" by varying the value of the byte written.

(您当然需要从管道中读取该字节,然后才能重新使用它.)

(You'll need to read the byte from the pipe before it can be re-used of course.)

这篇关于pthread_kill()vs pthread_cancel()终止为I/O阻塞的线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆