Volatile Variables in Optimized C

Ah, forgetting the volatile type qualifier when compiling with optimization enabled:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <pthread.h>
// compile with: gcc -O3 -lpthread volatile.c -o volatile
// Fix by using volatile:
// volatile int flag = 0;
int flag = 0;
void *update() {
flag = 1;
}
int main() {
pthread_t update_thread;
pthread_create(&update_thread, NULL, update, NULL);
while (!flag) {} // This will loop forever
pthread_join(update_thread, NULL);
}