From ea42da38258ee182201ecc6c9afb18a9ea46021c Mon Sep 17 00:00:00 2001 From: Dan Streetman Date: Wed, 19 May 2021 10:01:59 -0400 Subject: [PATCH] macro: add ONCE macro that evaluates to 1 one time Every location that this macro is used, it will be true the first time it's checked, then false each time after that. This can be useful for things such as one-time logging. --- src/fundamental/macro-fundamental.h | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/fundamental/macro-fundamental.h b/src/fundamental/macro-fundamental.h index 6ff8372f3cd..967518600d4 100644 --- a/src/fundamental/macro-fundamental.h +++ b/src/fundamental/macro-fundamental.h @@ -50,6 +50,17 @@ #define UNIQ_T(x, uniq) CONCATENATE(__unique_prefix_, CONCATENATE(x, uniq)) #define UNIQ __COUNTER__ +/* Note that this works differently from pthread_once(): this macro does + * not synchronize code execution, i.e. code that is run conditionalized + * on this macro will run concurrently to all other code conditionalized + * the same way, there's no ordering or completion enforced. */ +#define ONCE __ONCE(UNIQ_T(_once_, UNIQ)) +#define __ONCE(o) \ + ({ \ + static bool (o) = false; \ + __sync_bool_compare_and_swap(&(o), false, true); \ + }) + #undef MAX #define MAX(a, b) __MAX(UNIQ, (a), UNIQ, (b)) #define __MAX(aq, a, bq, b) \ -- 2.47.3