Busy waiting
Encyclopedia
In software engineering
Software engineering
Software Engineering is the application of a systematic, disciplined, quantifiable approach to the development, operation, and maintenance of software, and the study of these approaches; that is, the application of engineering to software...

, busy-waiting or spinning is a technique in which a process
Process (computing)
In computing, a process is an instance of a computer program that is being executed. It contains the program code and its current activity. Depending on the operating system , a process may be made up of multiple threads of execution that execute instructions concurrently.A computer program is a...

 repeatedly checks to see if a condition is true, such as whether keyboard
Computer keyboard
In computing, a keyboard is a typewriter-style keyboard, which uses an arrangement of buttons or keys, to act as mechanical levers or electronic switches...

 input is available, or if a lock
Lock (computer science)
In computer science, a lock is a synchronization mechanism for enforcing limits on access to a resource in an environment where there are many threads of execution. Locks are one way of enforcing concurrency control policies.-Types:...

 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. On modern computers with widely differing processor
Microprocessor
A microprocessor incorporates the functions of a computer's central processing unit on a single integrated circuit, or at most a few integrated circuits. It is a multipurpose, programmable device that accepts digital data as input, processes it according to instructions stored in its memory, and...

 speeds, spinning as a time delay technique often produces unpredictable results unless code is implemented to determine how quickly the processor can execute a "do nothing" loop.

Spinning can be a valid strategy in certain circumstances, most notably in the implementation of spinlock
Spinlock
In software engineering, a spinlock is a lock where the thread simply waits in a loop repeatedly checking until the lock becomes available. Since the thread remains active but isn't performing a useful task, the use of such a lock is a kind of busy waiting...

s within operating systems designed to run on SMP
Symmetric multiprocessing
In computing, symmetric multiprocessing involves a multiprocessor computer hardware architecture where two or more identical processors are connected to a single shared main memory and are controlled by a single OS instance. Most common multiprocessor systems today use an SMP architecture...

 systems. In general, however, spinning is considered an anti-pattern
Anti-pattern
In software engineering, an anti-pattern is a pattern that may be commonly used but is ineffective and/or counterproductive in practice.The term was coined in 1995 by Andrew Koenig,...

 and should be avoided, as processor time that could be used to execute a different task
Thread (computer science)
In computer science, a thread of execution is the smallest unit of processing that can be scheduled by an operating system. The implementation of threads and processes differs from one operating system to another, but in most cases, a thread is contained inside a process...

 is instead wasted on useless activity.

Example C code

The following C
C (programming language)
C is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system....

 code examples illustrate two threads that share a global integer
Integer
The integers are formed by the natural numbers together with the negatives of the non-zero natural numbers .They are known as Positive and Negative Integers respectively...

 i. The first thread uses busy-waiting to check for a change in the value of i:

  1. include
  2. include
  3. include
  4. 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 (i0) {
/* 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;
}

Busy-waiting alternatives
Most operating systems and threading libraries provide a variety of system call
System call
In computing, a system call is how a program requests a service from an operating system's kernel. This may include hardware related services , creating and executing new processes, and communicating with integral kernel services...

s that will block the process on an event, such as lock acquisition, timer changes, I/O
I/O
I/O may refer to:* Input/output, a system of communication for information processing systems* Input-output model, an economic model of flow prediction between sectors...

 availability or signals
Signal (computing)
A signal is a limited form of inter-process communication used in Unix, Unix-like, and other POSIX-compliant operating systems. Essentially it is an asynchronous notification sent to a process in order to notify it of an event that occurred. When a signal is sent to a process, the operating system...

. Using such calls generally produces the simplest, most efficient, fair, and race
Race condition
A race condition or race hazard is a flaw in an electronic system or process whereby the output or result of the process is unexpectedly and critically dependent on the sequence or timing of other events...

-free result. A single call checks, informs the scheduler of the event it is waiting for, inserts a memory barrier
Memory barrier
Memory barrier, also known as membar or memory fence or fence instruction, is a type of barrier and a class of instruction which causes a central processing unit or compiler to enforce an ordering constraint on memory operations issued before and after the barrier instruction.CPUs employ...

 where applicable, and may perform a requested I/O operation before returning. Other processes can use the CPU while the caller is blocked. The scheduler is given the information needed to implement priority inheritance
Priority inheritance
In real-time computing, priority inheritance is a method for eliminating priority inversion problems. Using this programming method, a process scheduling algorithm will increase the priority of a process to the maximum priority of any process waiting for any resource on which the process has a...

 or other mechanisms to avoid starvation
Resource starvation
In computer science, starvation is a multitasking-related problem, where a process is perpetually denied necessary resources. Without those resources, the program can never finish its task....

.

Busy-waiting itself can be made much less wasteful by using a delay function (e.g., sleep) found in most operating systems. This puts a thread to sleep for a specified time, during which the thread will waste no CPU time. If the loop is checking something simple then it will spend most of its time asleep and will waste very little CPU time.
Appropriate busy-wait usage

In low-level programming, busy-waits may actually be desirable. It may not be desirable or practical to implement interrupt-driven processing for every hardware device, particularly those that are seldom accessed. Sometimes it is necessary to write some sort of control data to hardware and then fetch device status resulting from the write operation, status that may not become valid until a number of machine cycles have elapsed following the write. The programmer could call an operating system delay function, but doing so may consume more time than would be expended in spinning for a few clock cycles waiting for the device to return its status.
See also

  • BogoMips
    BogoMips
    BogoMips is an unscientific measurement of CPU speed made by the Linux kernel when it boots, to calibrate an internal busy-loop...

  • volatile variable
    Volatile variable
    In computer programming, particularly in the C, C++, C#, and Java programming languages, a variable or object declared with the volatile keyword usually has special properties related to optimization and/or threading...

  • Polling (computer science)
    Polling (computer science)
    Polling, or polled operation, in computer science, refers to actively sampling the status of an external device by a client program as a synchronous activity. Polling is most often used in terms of input/output , and is also referred to as polled or software driven .Polling is sometimes used...

  • Spinlock
    Spinlock
    In software engineering, a spinlock is a lock where the thread simply waits in a loop repeatedly checking until the lock becomes available. Since the thread remains active but isn't performing a useful task, the use of such a lock is a kind of busy waiting...

  • Synchronization
    Synchronization
    Synchronization is timekeeping which requires the coordination of events to operate a system in unison. The familiar conductor of an orchestra serves to keep the orchestra in time....


External links
The source of this article is wikipedia, the free encyclopedia.  The text of this article is licensed under the GFDL.
 
x
OK