Kill a blocking thread in C's pthread gracefully?
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.
精彩评论