C++ 如何停止/中断 boost::thread?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10531810/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 14:10:45  来源:igfitidea点击:

How to stop/interrupt a boost::thread?

c++multithreadingboost

提问by wtm

I create a thread in a function,and in another function,I wanna stop this thread. I have tried like this:

我在一个函数中创建了一个线程,在另一个函数中,我想停止这个线程。我试过这样:

class Server
{
private:
     boost::thread* mPtrThread;
...

public:
     void createNewThread()
     {
        boost::thread t(...);
        mPtrThread = &t;
     }


     void stopThread()
     {
        mPtrThread->interrupt();
     }
}

But it's not work.How could I stop the thread?

但它不起作用。我怎么能停止线程?

回答by Aligus

If you want to use interrupt() you should define interruption points. Thread will be interrupted after calling interrupt() as soon as it reaches one of interruption points.

如果你想使用 interrupt() 你应该定义中断点。线程将在调用interrupt() 后,一旦到达中断点之一就会被中断。

回答by Eitan T

First of all, in createNewThread()you declare a boost::thread tin a localscope and assign its pointer to the class member mPtrThread. After createNewThread()finishes, tis destroyed and mPtrThread would hold an illegal pointer.

首先,在createNewThread()你声明了一个boost::thread t本地范围和它的指针分配给类成员mPtrThread。后createNewThread()完成,t被破坏,mPtrThread将举行非法指针。

I'd rather use something like mPtrThread = new boost::thread(...);

我宁愿使用类似的东西mPtrThread = new boost::thread(...)

You might also want to read this articleto learn more about multithreading in Boost.

您可能还想阅读本文以了解有关 Boost 中多线程的更多信息。