2016-12-16 92 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>