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

<think>嗯,用户让我介绍一下C语言中的单例设计模式。首先,我需要确认自己对这个主题的理解是否正确。单例模式是设计模式中的一种,确保一个类只有一个实例,并提供全局访问点。但是在C语言中,没有类的概念,所以需要用结构体和函数来模拟。 接下来,我得考虑用户可能的背景。他们可能已经了解一些C语言的基础知识,比如结构体、指针和静态变量,但可能对设计模式不太熟悉。因此,解释时需要结合C语言的特点,同时避免使用面向对象的术语,或者适当类比说明。 用户的需求是了解如何在C语言中实现单例模式。可能的场景包括需要全局唯一的资源管理器、日志系统或配置管理器等。这时候,用户可能希望确保这些资源只被实例化一次,避免重复创建导致的问题。 然后,我需要思考C语言实现单例的关键点。首先是静态变量来保存实例,确保其唯一性。然后是线程安全的问题,这在多线程环境中尤为重要。可能需要用到互斥锁或者pthread库中的相关函数。此外,延迟初始化也是一个重点,即实例在第一次使用时才创建,而不是在程序启动时就初始化。 可能存在的误区是,用户可能认为单例模式在C语言中的实现和C++或Java类似,但实际上由于语言特性的不同,实现方式会有差异。需要明确说明这些差异,比如静态变量的作用域和生命周期,以及如何通过函数封装来模拟类的行为。 另外,需要给出具体的代码示例,这样用户能更直观地理解。代码应该包括获取实例的函数、静态变量、线程安全机制和延迟初始化。同时,要解释代码的每一部分,确保用户明白每个步骤的作用。 还要考虑用户可能遇到的问题,比如内存泄漏,如何避免多次释放实例,或者如何处理多线程环境下的竞争条件。这时候可能需要提到双重检查锁定(Double-Checked Locking)模式,或者使用编译器特定的原子操作来优化性能。 最后,总结单例模式的优缺点,以及在C语言中使用时的注意事项。比如全局状态带来的测试困难,或者过度使用单例可能导致代码耦合度高等问题。这些信息能帮助用户更全面地评估是否适合在他们的项目中使用单例模式。</think>好的!在 C 语言中实现**单例模式Singleton Pattern)**需要手动模拟面向对象语言的特性(如私有构造函数、静态实例等)。单例模式的核心目标是确保一个类**仅有一个实例**,并提供全局访问点。以下是 C 语言实现单例模式的要点和示例: --- ### **关键实现步骤** 1. **静态实例**:使用 `static` 关键字隐藏实例,限制其作用域。 2. **延迟初始化**:第一次调用时创建实例,后续调用直接返回已存在的实例。 3. **线程安全**(可选):多线程环境下需通过锁(如 `pthread_mutex`)避免重复创建。 4. **全局访问函数**:提供获取单例实例的公共接口。 --- ### **基础实现示例** ```c #include <stdlib.h> // 单例结构体(可以是任意自定义类型) typedef struct { int data; } Singleton; // 静态实例指针(初始化为 NULL) static Singleton* instance = NULL; // 获取单例实例的函数 Singleton* get_instance() { if (instance == NULL) { // 首次调用时初始化 instance = (Singleton*)malloc(sizeof(Singleton)); instance->data = 0; // 初始化成员 } return instance; } ``` --- ### **线程安全改进版** 在 C11 标准后,可使用 `_Atomic` 或手动加锁(需链接 `pthread` 库): ```c #include <stdlib.h> #include <pthread.h> typedef struct { int data; } Singleton; static Singleton* instance = NULL; static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; Singleton* get_instance() { if (instance == NULL) { // 第一次检查(避免不必要的锁) pthread_mutex_lock(&mutex); // 加锁 if (instance == NULL) { // 第二次检查(确保线程安全) instance = (Singleton*)malloc(sizeof(Singleton)); instance->data = 0; } pthread_mutex_unlock(&mutex); } return instance; } ``` --- ### **使用示例** ```c int main() { Singleton* s1 = get_instance(); Singleton* s2 = get_instance(); // s1 和 s2 指向同一个实例 printf("s1地址: %p\ns2地址: %p\n", (void*)s1, (void*)s2); // 输出结果应为相同地址 return 0; } ``` --- ### **注意事项** 1. **内存释放**:单例实例通常在程序结束时释放,需手动管理(或结合 `atexit` 注册清理函数)。 2. **不可克隆**:避免通过拷贝构造函数或赋值操作创建新实例(C 语言中需手动规避)。 3. **全局状态风险**:单例是全局状态,过度使用可能导致代码耦合度高、测试困难。 --- ### **适用场景** - 需要全局唯一资源的场景(如日志系统、配置管理器、硬件访问接口)。 - 需要严格控制实例数量的场景(如线程池、数据库连接池)。 希望这个简洁的指南能帮助你理解 C 语言中的单例模式!如果有进一步问题,欢迎追问。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值