Last active
May 1, 2026 12:24
-
-
Save stedolan/c99894ef22431c3f560fcdd9040b73f5 to your computer and use it in GitHub Desktop.
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
| #include <stdatomic.h> | |
| #include <pthread.h> | |
| #include <stdio.h> | |
| struct { | |
| const char* _Atomic text[2]; | |
| char pad1[128]; | |
| int _Atomic flag; | |
| int _Atomic junk; | |
| } msg; | |
| static void send() { | |
| msg.text[1] = "sent"; | |
| msg.flag = 1; | |
| } | |
| static void recv() { | |
| int i = atomic_load_explicit(&msg.flag, memory_order_relaxed); | |
| //if (i == 1) { msg.junk = 1; } | |
| const char* m = atomic_load_explicit(&msg.text[i], memory_order_relaxed); | |
| printf("%s\n", m); | |
| //if (i == 1) { msg.junk = 1; } | |
| } | |
| /* The rest of this file is a test harness to run send() and recv() | |
| 1M times in parallel, resetting global state after each run */ | |
| struct { | |
| char pad1[128]; | |
| _Atomic unsigned send; | |
| char pad2[128]; | |
| _Atomic unsigned send_done; | |
| char pad3[128]; | |
| _Atomic unsigned recv; | |
| char pad4[128]; | |
| _Atomic unsigned recv_done; | |
| } sync; | |
| static void* sender_thread(void* unused) { | |
| while (1) { | |
| while (sync.send == sync.send_done) { } | |
| send(); | |
| sync.send_done ++; | |
| } | |
| } | |
| static void* receiver_thread(void* unused) { | |
| while (1) { | |
| while (sync.recv == sync.recv_done) { } | |
| recv(); | |
| sync.recv_done ++; | |
| } | |
| } | |
| int main () { | |
| pthread_t sender, receiver; | |
| pthread_create(&sender, NULL, &sender_thread, NULL); | |
| pthread_create(&receiver, NULL, &receiver_thread, NULL); | |
| for (int i = 1; i < 1000000; i++) { | |
| msg.text[0] = "waiting"; | |
| msg.text[1] = "UNINITIALIZED"; | |
| msg.flag = 0; | |
| sync.send = i; | |
| sync.recv = i; | |
| while (sync.send_done < i || sync.recv_done < i) { } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment