Wilfred Mutua Mworia's (Old) Blog (Now at Afrinnovator.com)


Information for tech enthusiasts, hobbyists, devs, tech startup founders and tech entrepreneurs



volatile int i; /* i is global, so it is visible to all functions.
it's also marked volatile, because it will change in
a way which is not predictable by the compiler (here:
from a different thread.) */

/* t1 uses spin lock to wait for i to change from 0. */
static void *f1()
while (i==0)
/* do nothing - just keep checking over and over. */
printf("i's value has changed to %d.\n", i);


static void *f2()
sleep(60); /* sleep for 60 seconds. */
i = 99;
printf("t2 changing the value of i to %d.\n", i);


int main()
int x;
pthread_t t1, t2;
i = 0; /* set global int i to 0. */

x = pthread_create(&t1, NULL, f1, NULL);
if (x != 0)
printf("pthread foo failed.\n");

x = pthread_create(&t2, NULL, f2, NULL);
if (x != 0)
printf("pthread bar failed.\n");

pthread_join(t1, NULL);
pthread_join(t2, NULL);
printf("all pthreads finished.\n");
return 0;

Filed under: IPC, Operating systems

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Mobile Web East Africa
TEDxYouthInspire 2010

My Flickr Photostream






More Photos
%d bloggers like this: