Singleton pattern C++ code
时间: 2023-02-26 22:26:11 浏览: 61
Here's an example of the Singleton pattern in C:
```
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
pthread_mutex_t lock;
typedef struct {
int id;
char name[20];
} SingletonData;
SingletonData* singleton_instance = NULL;
SingletonData* get_singleton_instance() {
pthread_mutex_lock(&lock);
if (singleton_instance == NULL) {
singleton_instance = (SingletonData*) malloc(sizeof(SingletonData));
singleton_instance->id = 1;
sprintf(singleton_instance->name, "Singleton");
}
pthread_mutex_unlock(&lock);
return singleton_instance;
}
int main() {
pthread_mutex_init(&lock, NULL);
SingletonData *data1 = get_singleton_instance();
SingletonData *data2 = get_singleton_instance();
printf("Data1: %d, %s\n", data1->id, data1->name);
printf("Data2: %d, %s\n", data2->id, data2->name);
pthread_mutex_destroy(&lock);
return 0;
}
```
In this example, the singleton instance is created only once and shared among all subsequent calls to `get_singleton_instance()`. The instance is created in a thread-safe manner using a mutex lock. The use of the mutex lock ensures that the singleton instance is only created once, even if multiple threads try to access it simultaneously.