Terminate thread c++11 blocked on read

前端 未结 2 1949
梦如初夏
梦如初夏 2021-02-10 20:59

I\'ve got the following code:

class Foo {
private:
    std::thread thread;
    void run();
    std::atomic_flag running;
    std::thread::native_handle_type nati         


        
2条回答
  •  清歌不尽
    2021-02-10 21:21

    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.

提交回复
热议问题