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

use*_*687 0 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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在主要我然后只需调用Test :: DoSomething(); 在这种情况下,变量'is_done'是否安全?如果不是我怎么能安全阅读呢?

Vit*_*meo 7

在这种情况下,全局变量'is_done'是否安全?

static并不意味着线程安全的.


如果不是我怎么能安全阅读呢?

你应该使用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};
Run Code Online (Sandbox Code Playgroud)