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:

    Hollywood keeps before its child audiences a string of glorified young heroes, everyone of whom is an unhesitating and violent Anarchist. His one answer to everything that annoys him or disparages his country or his parents or his young lady or his personal code of manly conduct is to give the offender a “sock” in the jaw.... My observation leads me to believe that it is not the virtuous people who are good at socking jaws.
    George Bernard Shaw (1856–1950)