Home > Back-end >  Ask blocking thread to exit
Ask blocking thread to exit

Time:01-12

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.

CodePudding user response:

See @dimich comment on the question. I use eventfd() and poll() to achieve the desired behavior, the man pages provide ready to use sample code.

CodePudding user response:

Signal handlers are indeed global.

As you observed, when a signal is generated for a process (as by kill or Ctrl C), rather than for a specific thread (as by pthread_kill or a floating point exception), the OS simply chooses one thread of that process to receive the signal. (Ref. POSIX.1-2017 Signal Concepts)

You can influence this choice by blocking (masking) the signal in all threads except the special one you want to receive the signal. Since thread signal masks are inherited, a typical approach is to mask the signal straight away in main() with pthread_sigmask(SIG_BLOCK, ...), and then to unmask it (SIG_UNBLOCK) in your special thread.

But this is a dubious approach. SIGINT seems the wrong signal to use, since it has well-established semantics — I expect a Ctrl C to terminate the foreground process group! Moreover, I/O multiplexing with a "notification fd," as others have suggested, is cleaner and less error-prone.

  • Related