我有这样一个类:
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/