#include <stdatomic.h>
#include <stdio.h>
#include <pthread.h>
atomic_int shared_var;
void* write_thread(void* arg) {
for (int i = 0; i < 10; ++i) {
atomic_store(&shared_var, i); // 原子存储操作
}
return NULL;
}
void* read_thread(void* arg) {
while (atomic_load(&shared_var) < 10) { // 原子加载操作
printf("shared_var: %d\n", atomic_load(&shared_var));
}
return NULL;
}
int main() {
pthread_t writer, reader;
pthread_create(&writer, NULL, &write_thread, NULL);
pthread_create(&reader, NULL, &read_thread, NULL);
pthread_join(writer, NULL);
pthread_join(reader, NULL);
return 0;
}