From 67cd0c44d23ec8d6b907f3b4966e488e2da09475 Mon Sep 17 00:00:00 2001 From: Yonggang Luo Date: Sat, 18 Jun 2022 23:55:49 +0800 Subject: [PATCH] util: Add api util_call_once_with_context This is used to remove the need of _MTX_INITIALIZER_NP in simple_mtx.h Signed-off-by: Yonggang Luo Reviewed-by: Jesse Natalie Reviewed-by: Jason Ekstrand Part-of: --- src/util/meson.build | 2 ++ src/util/u_call_once.c | 28 ++++++++++++++++++++++++++++ src/util/u_call_once.h | 27 +++++++++++++++++++++++++++ 3 files changed, 57 insertions(+) create mode 100644 src/util/u_call_once.c create mode 100644 src/util/u_call_once.h diff --git a/src/util/meson.build b/src/util/meson.build index 72652d04c66..4b73ef029c1 100644 --- a/src/util/meson.build +++ b/src/util/meson.build @@ -118,6 +118,8 @@ files_mesa_util = files( 'timespec.h', 'u_atomic.c', 'u_atomic.h', + 'u_call_once.c', + 'u_call_once.h', 'u_debug_describe.c', 'u_debug_describe.h', 'u_debug_refcnt.c', diff --git a/src/util/u_call_once.c b/src/util/u_call_once.c new file mode 100644 index 00000000000..a727a02f8b9 --- /dev/null +++ b/src/util/u_call_once.c @@ -0,0 +1,28 @@ +/* + * Copyright 2022 Yonggang Luo + * SPDX-License-Identifier: MIT + */ + +#include "u_call_once.h" + +struct util_call_once_context_t +{ + void *context; + util_call_once_callback_t callback; +}; + +static thread_local struct util_call_once_context_t call_once_context; + +static void util_call_once_with_context_callback(void) +{ + struct util_call_once_context_t *once_context = &call_once_context; + once_context->callback(once_context->context); +} + +void util_call_once_with_context(once_flag *once, void *context, util_call_once_callback_t callback) +{ + struct util_call_once_context_t *once_context = &call_once_context; + once_context->context = context; + once_context->callback = callback; + call_once(once, util_call_once_with_context_callback); +} diff --git a/src/util/u_call_once.h b/src/util/u_call_once.h new file mode 100644 index 00000000000..277ff721f32 --- /dev/null +++ b/src/util/u_call_once.h @@ -0,0 +1,27 @@ +/* + * Copyright 2022 Yonggang Luo + * SPDX-License-Identifier: MIT + * + * Extend C11 call_once to support context parameter + */ + +#ifndef U_CALL_ONCE_H_ +#define U_CALL_ONCE_H_ + +#include + +#include "c11/threads.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef void (*util_call_once_callback_t)(void *context); + +void util_call_once_with_context(once_flag *once, void *context, util_call_once_callback_t callback); + +#ifdef __cplusplus +} +#endif + +#endif /* U_CALL_ONCE_H_ */