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:

    Wise Draco comes, deep in the midnight roll
    Of black artillery; he comes, though late;
    In code corroborating Calvin’s creed
    And cynic tyrannies of honest kings;
    He comes, nor parlies; and the Town, redeemed,
    Gives thanks devout; nor, being thankful, heeds
    The grimy slur on the Republic’s faith implied,
    Which holds that Man is naturally good,
    And—more—is Nature’s Roman, never to be
    scourged.
    Herman Melville (1819–1891)