Humboldt-Universität zu Berlin - Mathematisch-Naturwissenschaftliche Fakultät - Systemanalyse

Beispiel thread-safe singleton

text/x-c++src Singleton.cpp — 1.3 KB

Dateiinhalt

//
//  main.cpp
//  once
//
//  Created by Klaus Ahrens on 11.06.12.
//  Copyright (c) 2012 HU Berlin. All rights reserved.
//

#include <iostream>
#include <thread>
#include <mutex>

class Singleton {
    static int counter;
    static std::mutex mutex;
    static std::shared_ptr<Singleton> instance_;
    static std::once_flag oflag;
    Singleton() {std::cout << "Singleton created" << std::endl; } // private !
    static void safe_create() {
        instance_.reset(new Singleton());
    }
public:
    static std::shared_ptr<Singleton> instance() {
        std::call_once(oflag, safe_create); // variadic args
        return instance_;
    }
    static void doSomeWork(){
        std::lock_guard<std::mutex> lock(mutex);
        for (int i=0; i<10000; ++i) --counter;
    }
    static int getCounter(){return counter;}
};

std::shared_ptr<Singleton> Singleton::instance_;
std::once_flag Singleton::oflag;
std::mutex Singleton::mutex;
int Singleton::counter = 40000;

void do_once()
{
    auto s = Singleton::instance();
    s->doSomeWork();
}

int main()
{
    std::thread t1(do_once);
    std::thread t2(do_once);
    std::thread t3(do_once);
    std::thread t4(do_once);
    
    t1.join();
    t2.join();
    t3.join();
    t4.join();
    std::cout<<Singleton::getCounter()<<std::endl;
}