Created
December 17, 2025 15:59
-
-
Save Patrolin/42446243b1645fb2540b4e79f18d34cb to your computer and use it in GitHub Desktop.
barrier.h
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #define atomic_load(address) __atomic_load_n(address, __ATOMIC_SEQ_CST) | |
| #define atomic_store(address, value) __atomic_store_n(address, value, __ATOMIC_SEQ_CST) | |
| #define atomic_fetch_add(address, value) __atomic_fetch_add(address, value, __ATOMIC_SEQ_CST) | |
| extern void wait_on_address(u32* address, u32 while_value); | |
| extern void wake_all_on_address(u32* address); | |
| typedef struct { | |
| u32 barrier; | |
| u32 barrier_counter; | |
| } SharedData; | |
| void barrier(SharedData* shared_data, u32 thread_count) { | |
| u32 barrier = atomic_load(&shared_data->barrier); | |
| u32 barrier_stop = barrier + thread_count; | |
| u32 barrier_counter = atomic_add_fetch(&shared_data->barrier_counter, 1); | |
| if (barrier_counter != barrier_stop) { | |
| /* NOTE: On windows, WaitOnAddress() "is allowed to return for other reasons", same thing with futex() on linux */ | |
| while (atomic_load(&shared_data->barrier) == barrier) { | |
| wait_on_address(&shared_data->barrier, barrier); | |
| } | |
| } else { | |
| atomic_store(&shared_data->barrier, barrier_stop); | |
| wake_all_on_address(&shared_data->barrier); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment