I\'ve got the following code:
class Foo {
private:
std::thread thread;
void run();
std::atomic_flag running;
std::thread::native_handle_type nati
As others have said, killing a running thread is a Bad Idea™.
However, in this case, you somehow know the thread is blocking on a read, and want it to stop.
A simple way of doing this is to use the "self pipe trick". Open a pipe, and have the thread block on a select()
or poll()
call, checking the read end of the pipe and the file descriptor being read. When you want the thread to stop, write a single byte to the write descriptor. The thread wakes up, sees the byte on the pipe and can then terminate.
This approaches avoids the undefined behaviour of killing a thread outright, allows you to use a blocking system call to avoid polling and is responsive to a termination request.