I have written a simple singleton application.
The following is my sample main class
// ThreadsafeSingletonUsingSemaphore.cpp : Defines the entry poi
You don't need to write all of that code. The easiest way to implement a threadsafe singleton is to use Scott Meyer's singleton idiom:
class Singleton {
int counter;
mutable std::mutex counter_guard;
Singleton() {}
public:
Singleton(const Singleton&) = delete;
Singleton(Singleton&&) = delete;
Singleton& operator=(const Singleton&) = delete;
Singleton& operator=(Singleton&&) = delete;
static Singleton& instance() {
static Singleton theInstance;
return theInstance;
}
void setCounter(int newVal) {
std::unique_lock lock(counter_guard);
counter = newVal;
}
void incrementCounter() {
std::unique_lock lock(counter_guard);
++counter;
}
int getCounter() const {
std::unique_lock lock(counter_guard);
return counter;
}
};
An even easier way would be to use a std::atomiccounter member variable. Then the mutex and lock guards can be omitted at all.