Search code examples
c++linuxmultithreadingsignals

Ask blocking thread to exit


I have a C++ thread (Linux) that uses blocking read to get data on some IO interface. I want to be able to abort read, and exit the thread.

Here https://stackoverflow.com/a/51742996/16317303 the general principle is explained, using pthread_kill to send a signal to a specific thread that interrupts the blocking read.

However, when I implement it that way, I am missing the "sending signal to specific thread" part. For example, CTRL+C in terminal does trigger the same handler as pthread_kill does, meaning that CTRL+C is not ending the console application anymore. For me it seems like a global handler for any SIGINT, and I don't know how I can make it that way that only this specific thread receives the signal and takes action, otherwise, when I use this pattern for different threads, I can't distinguish which thread receives a signal.


Solution

  • It's usually easier if you avoid signals as much as possible.

    Instead of doing a blocking read, you can make the file-descriptor non-blocking, then use poll (which is blocking) to wait for several things at the same time. You can make it wait for input data and wait for the shutdown signal at the same time. It returns if either one happens, and tells you which one happened.

    To make this work, the shutdown signal has to be something you can read data from, like a pipe or (as sctty suggested) an eventfd. When you write to the other end of the pipe, poll returns, saying "hey, you can read data from the pipe now!" but you don't want to actually read data from it, you just want to shut down (and close the pipe) when that happens.