c++ - 两个线程之间(共享)变量的 C++ 使用
问题描述
文件A.h
struct MyCounter{
int count;
};
class Counter {
public:
MyCounter mycounter;
void CreateThread(); // starts a thread
void DestroyThread();
void PrintCount(); // this function is called while the thread is running,
// reads the value of "count" and prints and is protected by a mutex while reading
};
class Singleton {
public:
Singleton& getInstance();
Counter counter;
};
文件B.cpp
// create static Singleton object say, S = Singleton->GetInstance()
void func1() {
S.counter.mycounter.count++; // My question is here: Is it okay to increment this counter here without using a mutex?
}
void func2() {
S.counter.CreateThread(); // Create a thread here
}
增加线程安全的“count”变量的最佳方法是什么?