Summary
In computer science and software engineering, busy-waiting, busy-looping or spinning is a technique in which a process repeatedly checks to see if a condition is true, such as whether keyboard input or a lock is available. Spinning can also be used to generate an arbitrary time delay, a technique that was necessary on systems that lacked a method of waiting a specific length of time. Processor speeds vary greatly from computer to computer, especially as some processors are designed to dynamically adjust speed based on current workload. Consequently, spinning as a time-delay technique can produce unpredictable or even inconsistent results on different systems unless code is included to determine the time a processor takes to execute a "do nothing" loop, or the looping code explicitly checks a real-time clock. In most cases spinning is considered an anti-pattern and should be avoided, as processor time that could be used to execute a different task is instead wasted on useless activity. Spinning can be a valid strategy in certain circumstances, most notably in the implementation of spinlocks within operating systems designed to run on SMP systems. 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 #include /* i is global, so it is visible to all functions. It makes use of the special type atomic_int, which allows atomic memory accesses. / atomic_int i = 0; /* f1 uses a spinlock to wait for i to change from 0. */ static void *f1(void p) { int local_i; / Atomically load current value of i into local_i and check if that value is zero / while ((local_i = atomic_load(&i)) == 0) { / do nothing - just keep checking over and over */ } printf("i's value has changed to %d.\n", local_i); return NULL; } static void *f2(void p) { int local_i = 99; sleep(10); / sleep for 10 seconds */ atomic_store(&i, local_i); printf("t2 has changed the value of i to %d.
About this result
This page is automatically generated and may contain information that is not correct, complete, up-to-date, or relevant to your search query. The same applies to every other page on this website. Please make sure to verify the information with EPFL's official sources.