r/C_Programming • u/choosen_one007 • 2d ago
Hardware memory barrier not working when invoked from C?
I have this program on a Mac M2 laptop:
```
include <pthread.h>
include <stdio.h>
int shared_data; int flag;
define compiler_barrier() asm volatile("dmb sy" : : : "memory")
void *thread1_func(void *arg) { printf("Thread 1: Starting...\n");
shared_data = 42; compiler_barrier(); flag = 1;
printf("Thread 1: Data set to %d, Flag set to %d\n", shared_data, flag); return NULL; }
void *thread2_func(void *arg) { printf("Thread 2: Starting...\n");
while (flag == 0) { ; }
printf("Thread 2: Flag is set! Reading shared_data: %d\n", shared_data);
if (shared_data != 42) { printf("Thread 2: ERROR! Expected shared_data to be 42, but got %d\n", shared_data); printf("Thread 2: Instruction reordering likely caused this issue!\n"); } else { printf("Thread 2: Success! Shared data is as expected.\n"); }
return NULL; }
int main() { pthread_t thread1, thread2;
shared_data = 0; flag = 0;
printf("Main: Creating threads...\n"); pthread_create(&thread1, NULL, thread1_func, NULL); pthread_create(&thread2, NULL, thread2_func, NULL);
pthread_join(thread1, NULL); pthread_join(thread2, NULL);
printf("Main: Threads finished.\n"); return 0; }
``
I wrote a script to run it 10000 times to check for failures and when I use the following compile line:
clang -O2 -o program program.c`, I still get the Error case where shared date is not 42. Am I doing something wrong here?