如何测试单身通用模板以确保线程安全?
我如何制作单身通用模板, 我该如何测试?
现在,我有兴趣用自己的眼睛看到2个调用get_instance()
的线程将获得相同的指针到同一单身人士。
// 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();
}
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();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论