How to stop a running thread safely on user request?

I'm in a scenario when I have to terminate a thread while the thread is running according to user action on GUI. I'm using Qt 4.5.2 on Windows. One way to do that is the following: class MyThread : public QThread { QMutex mutex; bool stop; public: MyThread() : stop(false) {} void requestStop() { QMutexLocker(&mutex); stop = true; } void run() { while(counter1--) { QMutexLocker(&mutex); if (stop) return; while(counter2--) { } } } }; Please note that the above code is minimal. The run function can take upto 20 seconds before finish so I want to avoid locking and unlocking the `mutex` variable in the loop. Is there any other way faster than this method. Thanks in advance.

以上就是How to stop a running thread safely on user request?的详细内容,更多请关注web前端其它相关文章!

赞(0) 打赏
未经允许不得转载:web前端首页 » CSS3 答疑

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

前端开发相关广告投放 更专业 更精准

联系我们

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏