Skip to content

Commit 18b7394

Browse files
add latch macros and use them for registering plugins
1 parent 562c89a commit 18b7394

File tree

2 files changed

+28
-13
lines changed

2 files changed

+28
-13
lines changed

extensions/core-extensions.c

Lines changed: 2 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -8,29 +8,20 @@
88
#include "registry.h"
99
#include "plugin.h"
1010

11-
CMARK_DEFINE_LOCK(extensions);
12-
1311
static int core_extensions_registration(cmark_plugin *plugin) {
14-
CMARK_INITIALIZE_AND_LOCK(extensions);
1512
cmark_plugin_register_syntax_extension(plugin, create_table_extension());
1613
cmark_plugin_register_syntax_extension(plugin,
1714
create_strikethrough_extension());
1815
cmark_plugin_register_syntax_extension(plugin, create_autolink_extension());
1916
cmark_plugin_register_syntax_extension(plugin, create_tagfilter_extension());
2017
cmark_plugin_register_syntax_extension(plugin, create_tasklist_extension());
21-
CMARK_UNLOCK(extensions);
2218
return 1;
2319
}
2420

25-
pthread_mutex_t registered_lock;
26-
static atomic_int registered_latch = 0;
27-
static _Atomic int registered = 0;
21+
CMARK_DEFINE_LATCH(registered);
2822

2923
void cmark_gfm_core_extensions_ensure_registered(void) {
30-
CMARK_INITIALIZE_AND_LOCK(extensions);
31-
if (!registered) {
24+
if (CMARK_CHECK_LATCH(registered)) {
3225
cmark_register_plugin(core_extensions_registration);
33-
registered = 1;
3426
}
35-
CMARK_UNLOCK(extensions);
3627
}

src/include/mutex.h

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,17 @@
88
#include <pthread.h>
99
#include <stdatomic.h>
1010

11-
static CMARK_INLINE void initialize_mutex_once(pthread_mutex_t *m, atomic_int *latch) {
11+
static CMARK_INLINE bool check_latch(atomic_int *latch) {
1212
int expected = 0;
13-
1413
if (atomic_compare_exchange_strong(latch, &expected, 1)) {
14+
return true;
15+
} else {
16+
return false;
17+
}
18+
}
19+
20+
static CMARK_INLINE void initialize_mutex_once(pthread_mutex_t *m, atomic_int *latch) {
21+
if (check_latch(latch)) {
1522
pthread_mutex_init(m, NULL);
1623
}
1724
}
@@ -26,12 +33,29 @@ pthread_mutex_lock(&NAME##_lock);
2633

2734
#define CMARK_UNLOCK(NAME) pthread_mutex_unlock(&NAME##_lock);
2835

36+
#define CMARK_DEFINE_LATCH(NAME) static atomic_int NAME = 0;
37+
38+
#define CMARK_CHECK_LATCH(NAME) check_latch(&NAME)
39+
2940
#else // no threading support
3041

42+
static CMARK_INLINE bool check_latch(int *latch) {
43+
if (!*latch) {
44+
*latch = 1;
45+
return true;
46+
} else {
47+
return false;
48+
}
49+
}
50+
3151
#define CMARK_DEFINE_LOCK(NAME)
3252
#define CMARK_INITIALIZE_AND_LOCK(NAME)
3353
#define CMARK_UNLOCK(NAME)
3454

55+
#define CMARK_DEFINE_LATCH static int NAME = 0;
56+
57+
#define CMARK_CHECK_LATCH check_latch(&NAME)
58+
3559
#endif // CMARK_THREADING
3660

3761
#endif // CMARK_MUTEX_H

0 commit comments

Comments
 (0)