A way to destroy “thread” class

前端 未结 8 1441
甜味超标
甜味超标 2021-02-06 18:22

Here is a skeleton of my thread class:

class MyThread {
public:
   virutal ~MyThread();

   // will start thread with svc() as thread entry point
   void start()         


        
8条回答
  •  南笙
    南笙 (楼主)
    2021-02-06 18:41

    Usually any OS-specific threads API will allow you to "join" a thread. That is, to block indefinitely on a thread handle until the thread functions returns.

    So,

    1. Signal the thread function to return (e.g. by setting a flag in its loop to false).
    2. Join the thread, to make sure the actual thread terminates before you try to delete the thread object.
    3. Then you can proceed with destruction of the thread object (you may also join in the destructor, though some people object to blocking destructors.).

    I've had a project before with a similar "thread worker" class and a corresponding "work item" class (a-la Java's Thread and Runnable, except thread does not terminate but waits for a new Runnable object to be executed).

    In the end, there was no difference if you join in a separate "shutdown" function or in the destructor, except a separate function is a bit more clear.

    1. If you join in a destructor and a thread blocks, you will wait indefinitely.
    2. If you join in a separate function and a thread blocks, you will wait indefinitely.
    3. If you detach the thread and let it finish on its own, it will usually block application from exiting, so you will wait indefinitely.

    So there is no straightforward way to make a thread behave like a regular C++ object and ignore its OS thread semantics, unless you can guarantee that your thread code can terminate almost immediately when notified to do so.

提交回复
热议问题