我对 C++ 中的单例和多线程编程有疑问以下您可以看到带有名为 shared 的变量的单例类的示例代码。
我创建了 1000 个线程来修改(+1)我的 Singleton 全局实例的该变量。shared 的最终值是 1000,但我希望这个值低于 1000,因为我没有保护这个变量的并发性。
代码真的是线程安全的,因为类是 Singleton 还是碰巧很幸运,值是 1000,但它完全可以小于 1000?
#include <iostream>
using namespace std;
class Singleton {
private:
Singleton() {shared = 0;};
static Singleton * _instance;
int shared;
public:
static Singleton* Instance();
void increaseShared () { shared++; };
int getSharedValue () { return shared; };
};
// Global static pointer used to ensure a single instance of the class.
Singleton* Singleton::_instance = NULL;
Singleton * Singleton::Instance() {
if (!_instance) {
_instance = new Singleton;
}
return _instance;
}
void * myThreadCode (void * param) {
Singleton * theInstance;
theInstance = Singleton::Instance();
theInstance->increaseShared();
return NULL;
}
int main(int argc, const char * argv[]) {
pthread_t threads[1000];
Singleton * theInstance = Singleton::Instance();
for (int i=0; i<1000; i++) {
pthread_create(&threads[i], NULL, &myThreadCode, NULL);
}
cout << "The shared value is: " << theInstance->getSharedValue() << endl;
return 0;
}