c语言多线程单例模式

c语言多线程单例模式

懒汉模式:

#include <pthread.h>
#include <stdio.h>

pthread_once_t once = PTHREAD_ONCE_INIT;

class Singleton
{
protected:
    static Singleton *_instance;
    static void mutex_init(void); //initialize mutex at beginning
    static pthread_mutex_t mutex;
    Singleton() {}
public:
    static Singleton* getInstance();
};

Singleton* Singleton::_instance = NULL;
pthread_mutex_t Singleton::mutex;

void Singleton::mutex_init(void)
{
    printf("in mutex_init\n");
    pthread_mutex_init(&mutex, NULL);
}

Singleton* Singleton::getInstance()
{
    pthread_once(&once, mutex_init);
    if(_instance == NULL)
    {
        pthread_mutex_lock(&mutex);
        if(_instance == NULL)
            _instance = new Singleton();
        pthread_mutex_unlock(&mutex);
    }
    return _instance;
}

void* thrFunc1(void *arg)
{
    printf("in thrFunc1\n");
    auto p = Singleton::getInstance();
    printf("address: %p\n", p);
    return NULL;
}

int main()
{
    pthread_t pid1, pid2;
    pthread_create(&pid1, NULL, thrFunc1, NULL);
    pthread_create(&pid2, NULL, thrFunc1, NULL);
    pthread_join(pid1, NULL);
    pthread_join(pid2, NULL);
}

输出结果:
in thrFunc1
in thrFunc1
in mutex_init
address: 0x100300070
address: 0x100300070

饿汉模式:

#include <stdio.h>
#include <pthread.h>

class Singleton
{
public:
    static Singleton* getInstance();
protected:
    Singleton() {};
    static Singleton *_instance;
};

Singleton* Singleton::_instance = new Singleton();
Singleton* Singleton::getInstance()
{
    return _instance;
}

void* thrFunc1(void *arg)
{
    auto p = Singleton::getInstance();
    printf("address: %p\n", p);
    return NULL;
}
int main()
{
    pthread_t pid1, pid2;
    pthread_create(&pid1, NULL, thrFunc1, NULL);
    pthread_create(&pid2, NULL, thrFunc1, NULL);
    pthread_join(pid1, NULL);
    pthread_join(pid2, NULL);
}

输出结果:
address: 0x1003002e0
address: 0x1003002e0

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值