如何防止多个线程在cpp中同时使用单例类实例

dan*_*dhi 0 c++ singleton multithreading design-patterns

我正在编写一个线程安全的单例类,如下所示.以下实现确保只创建了一个类的实例.我的用例是我在多线程环境中使用此实例,其中每个线程可以getInstance()使用该实例调用并执行一些工作.我的问题是如何确保在特定时间只有一个线程正在使用该实例,以防止在多个线程同时尝试使用单个实例时可能发生的竞争条件.

class Singleton {
    Singleton() {}
    Singleton(const Singleton&) = delete;
    Singleton& operator=(const Singleton&) = delete;
 public:
    static Singleton& getInstance() {
        static Singleton s;
        return s;
    }
};
Run Code Online (Sandbox Code Playgroud)

Nat*_*ica 5

你可以做的一件事就是通过锁定互斥锁来使其所有成员的线程安全.

class Singleton {
    Singleton() {}
    Singleton(const Singleton&) = delete;
    Singleton& operator=(const Singleton&) = delete;
    std::mutex my_mutex_member;
 public:
    static Singleton& getInstance() {
        static Singleton s;
        return s;
    }
    void my_singleton_cool_function()
    {
        std::lock_guard<std::mutex> lg(my_mutex_member);
        // cool code here
    }
};
Run Code Online (Sandbox Code Playgroud)

在上面的示例lg中将锁定互斥锁并在函数的末尾,当lg被破坏时,析构函数将解锁互斥锁.这意味着只有一个线程可以同时运行该功能.这允许所有线程都具有对单例的引用,并且仅在两个或多个线程同时尝试执行相同操作时才会阻塞.