c++ - 如何使类静态变量线程安全

标签 c++ multithreading

我有这样一个类:

class Test
{
private:
    Test() {}
    static bool is_done;
    static void ThreadFunction();
public:
    static void DoSomething();
}


bool Test::is_done = true;

void Test::DoSomething()
{
    std::thread t_thread(Test::ThreadFunction);

    while (true) {
        if (is_done) {
            //do something else
            is_done = false;
        }

        if (/*something happened*/) { break; }
    }

    // Finish thread.
    t_thread.join();
}

void Test::ThreadFunction()
{
    while (true) {
        if (/*something happened*/) {
            is_done = true;
        }
    }
}

然后在 main 中我只调用 Test::DoSomething();在这种情况下变量'is_done'是线程安全的吗?如果不是,我怎样才能保证阅读安全?

最佳答案

Is global variable 'is_done' in this case thread safe?

没有。 static并不意味着线程安全。


If its not how can I make reading it safe?

你应该使用 std::atomic<bool> :

class Test
{
private:
    Test() {}
    static std::atomic<bool> is_done;
    static void ThreadFunction();
public:
    static void DoSomething();
}

std::atomic<bool> Test::is_done{true};

关于c++ - 如何使类静态变量线程安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41189501/

相关文章:

c++ - 如何将 NSObject 传递给 objective-c 中的 cpp 代码

c++ 使用声明、作用域和访问控制

c++ - 错误 C2146 : syntax error : missing ',' before identifier 'A1'

C++线程线程的最大CPU

java - 为什么我的线程没有启动?

C++ : First User Input Prompt Is Skipped

c++ - 为什么类成员数据必须是静态的才能被模板化类的模板化结构成员访问?

c - 互斥锁永远锁定函数中的一个值

android - 使用 while 循环在线程中 sleep ,在 UIThread 中不 sleep

c# - 抵御 System.Collections.Concurrent.ConcurrentDictionary 中的竞争条件