繁体   English   中英

这是启动和停止线程的安全方法吗?

[英]Is this a safe way to start and stop a thread?

假设我有一个名为foo的类,它在线程中执行一些任务。 我想按照我认为合适的方式开始和停止这项任务。 我的代码如下:

class foo
{

public:
    foo() {};
    ~foo() {};

    void start_thread() {
        thread_active = true;
        the_thread = std::thread(&foo::execute, this);
    }
    void stop_thread() {
        thread_active = false;
        the_thread.join();
    }

private:
    void execute() {
        while (thread_active)
            std::cout << "executing...\n";
    }

    std::thread the_thread;
    bool thread_active;
};

我这样称呼它:

int main()
{
    foo bar;
    bar.start_thread();
    Sleep(1000);
    bar.stop_thread();
}

这是一种安全的方法吗?

不,这不是一种安全的方式。

原因是thread_active成员在读取和写入时没有从多个线程同步访问,您应该声明它std::atomic_bool或使用某种其他形式的同步。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM