2016-12-16 91 views
0

我有一个类,像这样:如何使类的静态变量线程安全

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; 
     } 
    } 
} 

在主我则只是调用测试:: DoSomething的();在这种情况下,变量'is_done'是否线程安全?如果它不是我怎么能让它安全读取?

+0

你要等待is_done是真/假的地方? –

+0

@RichardHodges我在测试:: DoSomething() – user1806687

+0

你可以在那里抛出一个静态互斥体,使其线程安全 –

回答

5

在这种情况下,全局变量'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}; 
+0

请注意,如果您在一次敏感操作中进行多次读取/写入,则使其成为“原子”可能不一定有效,例如, 'if(Test :: is_done){Test :: is_done = false; ...}' – qxz

+0

应该可能使用lock_guard进行此类操作。 –

2

我不能尚未就此发表评论,但你尝试过使用原子能?

例如std::atomic<bool>