Busy Waiting - Example C Code

Example C Code

The following C code examples illustrate two threads that share a global integer i. The first thread uses busy-waiting to check for a change in the value of i:

#include #include #include #include volatile int i = 0; /* i is global, so it is visible to all functions. It's also marked volatile, because it may change in a way which is not predictable by the compiler, here from a different thread. */ /* f1 uses a spinlock to wait for i to change from 0. */ static void *f1(void *p) { while (i==0) { /* do nothing - just keep checking over and over */ } printf("i's value has changed to %d.\n", i); return NULL; } static void *f2(void *p) { sleep(60); /* sleep for 60 seconds */ i = 99; printf("t2 has changed the value of i to %d.\n", i); return NULL; } int main { int rc; pthread_t t1, t2; rc = pthread_create(&t1, NULL, f1, NULL); if (rc != 0) { fprintf(stderr,"pthread f1 failed\n"); return EXIT_FAILURE; } rc = pthread_create(&t2, NULL, f2, NULL); if (rc != 0) { fprintf(stderr,"pthread f2 failed\n"); return EXIT_FAILURE; } pthread_join(t1, NULL); pthread_join(t2, NULL); puts("All pthreads finished."); return 0; }

In a use case like this, one can consider using C11's condition variables.

Read more about this topic:  Busy Waiting

Famous quotes containing the word code:

    ...I had grown up in a world that was dominated by immature age. Not by vigorous immaturity, but by immaturity that was old and tired and prudent, that loved ritual and rubric, and was utterly wanting in curiosity about the new and the strange. Its era has passed away, and the world it made has crumbled around us. Its finest creation, a code of manners, has been ridiculed and discarded.
    Ellen Glasgow (1873–1945)