Is it possible to kill a spinning thread?

前端 未结 9 1485
遥遥无期
遥遥无期 2021-01-20 19:09

I am using ZThreads to illustrate the question but my question applies to PThreads, Boost Threads and other such threading libraries in C++.

class MyClass: p         


        
9条回答
  •  北海茫月
    2021-01-20 19:34

    If you need to kill a thread, consider using a process instead.

    Especially if you tell us that your "thread" is a while (true) loop that may sleep for a long period of time performing operations that are necessarily blocking. To me, that indicate a process-like behavior.

    Processes can be terminated in a various number of ways at almost any time and always in a clean way. They may also offer more reliability in case of a crash.

    Modern operating systems offer an array of interprocess communications facilities: sockets, pipes, shared memory, memory mapped files ... They may even exchange file descriptors.

    Good OSes have copy-on-write mechanism, so processes are cheap to fork.

    Note that if your operations can be made in a non-blocking way, then you should use a poll-like mechanism instead. Boost::asio may help there.

提交回复
热议问题