我有一个类,像这样:如何使类的静态变量线程安全
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
你可以在那里抛出一个静态互斥体,使其线程安全 –