#include <iostream>
#include <thread>
#include <chrono>
#include <mutex>
using namespace std;
class mySingleton {
private:
mySingleton() {
cout<<"Singleton initialization"<<endl;
this_thread::sleep_for(chrono::milliseconds(10000));
cout<<"Singleton initialization terminated"<<endl;
}
public:
static mySingleton* getInstance() {
static mySingleton* instance = NULL;
static mutex mtx;
if(instance == NULL){
mtx.lock();
if(instance == NULL)
instance = new mySingleton();
mtx.unlock();
}
return instance;
}
};
void *create(void* x) {
cout << "Thread 1 " << endl;
this_thread::sleep_for(chrono::milliseconds(3000));
x = mySingleton::getInstance();
pthread_exit(NULL);
}
int main(){
mySingleton* x = NULL;
pthread_t t1;
pthread_create(&t1, NULL, create, (void *)x);
cout << "thread 1 created"<<endl;
this_thread::sleep_for(chrono::milliseconds(1000));
cout << "thread 2 is about to start"<<endl;
while(x == NULL){
cout <<"instance not created yet"<<endl;
this_thread::sleep_for(chrono::milliseconds(1000));
}
cout << "instance created\n";
pthread_exit(NULL);
return 0;
}
while
语句永远循环,这就是为什么(我想)线程t1更新指针的本地副本,但是如何使主线程或任何其他线程看到mySingleton对象已创建?] >
#include
正如你说的,
x = mySingleton::getInstance();
只是在更新本地复制的参数。
您应该将pointer to]传递给x
中的变量main()
。pthread_create(&t1, NULL, create, (void *)&x); // add & before x
并通过传递的指针更新指向的对象
*(mySingleton**)x = mySingleton::getInstance(); // add cast and dereference