Reputation: 11
I have a pthread which does an indefinite polling on some file descriptors, with negative timeout parameter.
From the main thread, I would like to be able to indicate to the polling thread that it should exit.
I did some research and found the following approaches:
Use pthread_cancel(): This was discouraged as it might lead to unintended consequences of not clearing any held resources or mutexes
Use a variable as a flag and set it in the main thread. The polling thread checks this flag every iteration and if set, exits by calling pthread_exit(). This approach won't work because my polling thread doesn't loop, but simply blocks indefinitely, waiting on the file descriptors.
Can anyone suggest an elegant solution to this problem ?
Thanks! ASM
Upvotes: 1
Views: 548
Reputation: 119847
You can send the blocking thread a signal (e.g. SIGUSR1
) with pthread_kill()
. The select
call should then return a negative value and set errno
to EINTR
. Don't forget to set a handler for the signal you send.
Upvotes: 1
Reputation: 239011
You can create an anonymous pipe with pipe(2)
and have the file-descriptor-watching thread add the read end to its polled file descriptors, exiting when that file descriptor reports EOF. The main thread then just closes the write end when it wants the thread to exit.
Upvotes: 5