开发者

Kill a blocking thread in C's pthread gracefully?

开发者 https://www.devze.com 2023-03-13 07:22 出处:网络
Say I have a thread that\'s something like this: void my_thread(char *device_name) { int fd = open(device_name, O_RDONLY);

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 usi开发者_如何学Cng 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!


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号