Skip to content

Instantly share code, notes, and snippets.

@aprell
Created March 7, 2012 15:33
Show Gist options
  • Save aprell/1993822 to your computer and use it in GitHub Desktop.
Save aprell/1993822 to your computer and use it in GitHub Desktop.
When "volatile" becomes necessary
#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