本文主要是介绍wow-singleton文件说明,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
wow-singleton文件说明
- 项目地址:https://gitee.com/wow-iot/wow-iot7
- 内部使用atomic原子操作,支持接口初始化与退出只被执行1次 ,不被重复执行;
初始化与退出:
typedef struct{singleton_exit_func_t exit; atomic_t instance;
}__data_aligned__ Singleton_T;static bool gb_singletonInited = false;
static Singleton_T gst_singletons[SINGLETON_TYPE_MAXN] = {{0}};int _wow_singleton_init(void)
{if(gb_singletonInited == false){memset(&gst_singletons, 0, sizeof(gst_singletons)); gb_singletonInited = true;}return 0;
}int _wow_singleton_exit(void)
{size_t i = SINGLETON_TYPE_MAXN;while (i--){if (gst_singletons[i].exit){int instance = atomic_get(&gst_singletons[i].instance);if (instance && instance == 1 && gst_singletons[i].exit) { gst_singletons[i].exit();}}}memset(&gst_singletons, 0, sizeof(gst_singletons));return 0;
}
接口执行
int wow_singleton_instance(SingletonType_E eIndex, singleton_init_func_t fInit, singleton_exit_func_t fExit)
{CHECK_RET_VAL_P(eIndex < SINGLETON_TYPE_MAXN, -PARAM_INPUT_ARG_INVALID, "param input arg invalid!\n");CHECK_RET_VAL_P(fInit, -PARAM_INPUT_FUNC_IS_NULL, "param input func invalid!\n");bool instance = atomic_compare_and_swap_bool(&gst_singletons[eIndex].instance, 0, 1);CHECK_RET_VAL(instance && gst_singletons[eIndex].instance == 1,0);CHECK_RET_VAL_P(fInit() == 0, -WOW_CB_FAILED,"eIndex(%d) init failed!\n",eIndex);atomic_set(&gst_singletons[eIndex].instance,1);gst_singletons[eIndex].exit = fExit;return 0;
}
这篇关于wow-singleton文件说明的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!