c++ , pthread and static callbacks. “this” returns a pointer to the base class inctead of the derived one (part 2)

[亡魂溺海] 提交于 2019-12-02 07:18:18

You need to wait for the thread to terminate before you return from main, because that destroys your object.

Otherwise you have a race condition:

  1. The thread is started.
  2. thrrdupd starts to be destoyed as you leave main.
  3. ~ThreadedWrite runs; at this point the object is no longer a ThreadedWrite but a cppthread.
  4. ~cppthread runs and waits for the thread.
  5. The thread calls the callback and because the object now has dynamic type cppthread, cppthread::threadedFunc is called.

It is possible that 5. might happen before 3., in which case you will get the expected output.

If you make sure you wait for the thread to finish at step 3. then it will work fine. Perhaps you could call terminate inside ~ThreadedWrite?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!