A way to destroy “thread” class

前端 未结 8 1255
甜味超标
甜味超标 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:31

    You first need a way to communicate with the thread to tell it to shut down. The best mechanism to do this depends on what svc() is doing. If, for example, it is looping on a message queue, you could insert a "please stop" message in that queue. Otherwise, you could simply add a member bool variable (and synchronize access to it) that is periodically checked by the svc(), and set by the thread wanting to destroy the object. Your could add a pure virtual stop() function to your base class, giving the implementor a clear signal that it has to implement svc() to make its class "runnable", and to implement stop() to make it "stoppable".

    After asking the thread to stop, you must wait for it to exit before destroying the object. Again, there are several ways to do this. One is to make the stop() function blocking. It could wait, for example, for a "ok, I'm really stopped now" condition variable to be set by the thread running svc(). Alternatively, the caller could "wait" on the thread running svc(). The way to "wait" is platform dependent.

提交回复
热议问题