如何测试单身通用模板以确保线程安全?

发布于 2025-01-26 11:40:35 字数 1316 浏览 1 评论 0原文

我如何制作单身通用模板, 我该如何测试?

现在,我有兴趣用自己的眼睛看到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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文