优雅地杀死 C 的 pthread 中的阻塞线程?
假设我有一个类似这样的线程:
void my_thread(char *device_name) {
int fd = open(device_name, O_RDONLY);
struct input_event ev;
while(1) {
read(fd, &ev, sizeof(struct input_event));
/* do something */
}
}
如何停止这样的线程?一种方法是使用 pthread_cancel,但我宁愿做得更优雅。也许类似于 pthread_kill 之类的东西?然而,在这种情况下,读取方法是否会解除阻塞(我认为应该如此)以及线程将如何处理信号?或者是应该处理它的进程?
我将非常感谢您的建议!
Say I have a thread that's something like this:
void my_thread(char *device_name) {
int fd = open(device_name, O_RDONLY);
struct input_event ev;
while(1) {
read(fd, &ev, sizeof(struct input_event));
/* do something */
}
}
How do I stop such a thread? One way is using pthread_cancel
, but I'd rather do it more gracefully. Something like pthread_kill
perhaps? In such case, however, would the read method unblock (as I presume it should) and how would the thread handle the signal? Or is it the process that should handle it?
I'd be very grateful for an advice!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的问题实际上是“如何中断其他线程的阻塞系统调用”。
尝试寻找它。以下是类似的讨论之一:关闭阻塞 UDP 的正确方法套接字
You problem is actually "how to interrupt blocking system call from other thread".
Try searching for it. Here is one of the similar discussions: Proper way to close a blocking UDP socket
答案是不要做任何会在没有超时的情况下阻塞的事情。对于 IO,在知道调用不会阻塞之前,不应调用 read()。例如,首先在路径上使用 poll() 或 select() 以确定状态。
The answer to this is to not do anything that will block without a timeout. For IO, you shouldn't call read() until you know the call will not block. For example, use poll() or select() on the path first in order to determine the status.
你无法优雅地杀死一个线程。如果您想要干净退出,请确保线程根据某种条件退出。
You can't kill a thread gracefully. If you want clean exit, make sure the thread exits based on some condition.