问题描述
在C中创建单身人士的最佳方法是什么?并发解决方案会很好.
我知道C不是您将使用Singleton的母语.
推荐答案
首先,C不适合OO编程.如果您这样做,您将一路战斗.其次,单例只是带有一些封装的静态变量.因此,您可以使用静态全局变量.但是,全球变量通常存在太多与之相关的疾病.否则,您可以使用函数本地静态变量,例如:
int *SingletonInt() { static int instance = 42; return &instance; }
或更智能的宏:
#define SINGLETON(t, inst, init) t* Singleton_##t() { \ static t inst = init; \ return &inst; \ } #include <stdio.h> /* actual definition */ SINGLETON(float, finst, 4.2); int main() { printf("%f\n", *(Singleton_float())); return 0; }
最后,请记住,单身人士大部分被滥用.很难使它们正确,尤其是在多线程环境下...
其他推荐答案
您不需要. C已经有全局变量,因此您不需要工作来模拟它们.
其他推荐答案
与C ++版本几乎相同.只需具有返回实例指针的函数即可.它可以是函数内部的静态变量.根据平台,用关键部分或Pthread Mutex包裹功能主体.
#include <stdlib.h> struct A { int a; int b; }; struct A* getObject() { static struct A *instance = NULL; // do lock here if(instance == NULL) { instance = malloc(sizeof(*instance)); instance->a = 1; instance->b = 2; } // do unlock return instance; };
请注意,您也需要一个函数来释放单例.特别是如果它抓住任何在流程退出时未自动发布的系统资源.
问题描述
What's the best way to create a singleton in C? A concurrent solution would be nice.
I am aware that C isn't the first language you would use for a singleton.
推荐答案
First, C is not suitable for OO programming. You'd be fighting all the way if you do. Secondly, singletons are just static variables with some encapsulation. So you can use a static global variable. However, global variables typically have far too many ills associated with them. You could otherwise use a function local static variable, like this:
int *SingletonInt() { static int instance = 42; return &instance; }
or a smarter macro:
#define SINGLETON(t, inst, init) t* Singleton_##t() { \ static t inst = init; \ return &inst; \ } #include <stdio.h> /* actual definition */ SINGLETON(float, finst, 4.2); int main() { printf("%f\n", *(Singleton_float())); return 0; }
And finally, remember, that singletons are mostly abused. It is difficult to get them right, especially under multi-threaded environments...
其他推荐答案
You don't need to. C already has global variables, so you don't need a work-around to simulate them.
其他推荐答案
It's the same as the C++ version pretty much. Just have a function that returns an instance pointer. It can be a static variable inside the function. Wrap the function body with a critical section or pthread mutex, depending on platform.
#include <stdlib.h> struct A { int a; int b; }; struct A* getObject() { static struct A *instance = NULL; // do lock here if(instance == NULL) { instance = malloc(sizeof(*instance)); instance->a = 1; instance->b = 2; } // do unlock return instance; };
Note that you'd need a function to free up the singleton too. Especially if it grabs any system resources that aren't automatically released on process exit.