'How to test a singleton generic template to be thread safe?
How do I make Singleton generic template, and how can I test it?
Right now I am interested in seeing with my own eyes that 2 threads that invoke get_instance()
will get the same pointer to the same singleton.
// g++ singleton.cpp -std=c++2a -pthread -o singleton
#include <iostream>
#include <string>
#include <vector>
#include <memory>
#include <mutex>
#include <thread>
#include <chrono>
#include <pthread.h>
#include <future>
using namespace std;
template <class T>
struct Singleton
{
Singleton(const Singleton &) = delete;
Singleton &operator=(const Singleton &) = delete;
static T &get_instance()
{
static T _{allow()};
return _;
}
private:
struct allow
{
};
protected:
Singleton(allow) {}
};
class A : public Singleton<A>
{
using Singleton<A>::Singleton;
// Rest of functionality for class A
};
int main()
{
auto &x = Singleton<A>::get_instance();
auto &y = A::get_instance();
printf("%p\n", &x);
printf("%p\n", &y);
void *p1;
void *p2;
// thread worker1(Singleton<A>::get_instance);
// thread worker2(Singleton<A>::get_instance);
// worker1.join();
// worker2.join();
printf("%p\n", p1);
printf("%p\n", p2);
// compiler error
// auto z = A();
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|