Created
March 7, 2012 15:33
-
-
Save aprell/1993822 to your computer and use it in GitHub Desktop.
When "volatile" becomes necessary
This file contains 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 <stdio.h> | |
#include <stdlib.h> | |
#include <unistd.h> | |
#include <pthread.h> | |
static int shared; | |
static void *thread_func(void *args) | |
{ | |
int ID = *(int *)args; | |
printf("Hello from thread %d!\n", ID); | |
if (ID != 0) { | |
// Forces the compiler to load from memory | |
while (*(volatile int *)&shared == 0) ; | |
printf("shared is %d\n", shared); | |
} else { | |
sleep(1); | |
shared = 42; | |
} | |
printf("Bye from thread %d!\n", ID); | |
return NULL; | |
} | |
int main(void) | |
{ | |
pthread_t thread; | |
int IDs[2] = { 0, 1 }; | |
pthread_create(&thread, NULL, thread_func, &IDs[1]); | |
thread_func(&IDs[0]); | |
pthread_join(thread, NULL); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment