我如何在线程中初始化对象,然后在其他地方使用它?

问题描述 投票:1回答:1
#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 #include #include #include 使用命名空间std;类mySingleton {私有:mySingleton(){cout <

c++ constructor
1个回答
3
投票

正如你说的,

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
© www.soinside.com 2019 - 2024. All rights reserved.