我有一個類,像這樣:如何使類的靜態變量線程安全
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'是否線程安全?如果它不是我怎麼能讓它安全讀取?
你要等待is_done是真/假的地方? –
@RichardHodges我在測試:: DoSomething() – user1806687
你可以在那裏拋出一個靜態互斥體,使其線程安全 –