中断自己的线程是否安全?

时间:2013-12-20 01:50:43

标签: c++ multithreading boost

我有一个创建线程并存储它的类。在做一些事情时,这个线程会注意到一些错误,通知类并自行中断。

class foo {
public:
    enum mode {
        run=0,
        booboo,
        stop
    };

    foo() {
        th_ = boost::thread(boost::bind(&foo::bar, this));
        mode_ = run;
    }

    ~foo() {
        stop();
    }

    void stop() {
        mode_ = stop;
        th_.join();
    }

    void bar {
        for(;;) {
            if(mode_ == stop)
            return;

            if(error) {
                mode_ = booboo;
                th_.interrupt();

                // the sleep is the interruption point
                boost::this_thread::sleep_for(boost::chrono::nanoseconds(0));
            }

            // do some stuff
        }
    }

private:
    boost::thread th_;
    mode          mode_;
};

根据boost::thread.interrupt,没有迹象表明这不起作用。如果我理解正确,interrupt将标记线程在下一个interruption_point中断它,在我的情况下是sleep_for的调用。

在我的机器和操作系统上,它正在运行,所以我的问题是,这样做是否安全?

0 个答案:

没有答案
相关问题