Espera activa
De Wikipedia, la enciclopedia libre
En Informática, se denomina espera activa a una técnica donde el proceso repetidamente verifica una condición, tal como esperar una entrada de teclado o si el ingreso a una Sección crítica está habilitado. Puede ser una estrategia valida en algunas circunstancias especiales, sobre todo en la sincronización de procesos en los sistemas con múltiples procesadores (SMP). En general, debe ser evitada, ya que consume tiempo de CPU sin realizar ninguna operación.
[editar] Ejemplo en Código C
Este código muestra dos threads (hilos) que comparten la variable global entera i. El primer thread usa espera activa para chequear un cambio en el valor de i.
#include <stdio.h> #include <pthread.h> #include <unistd.h> volatile int i; /* i is global, so it is visible to all functions. it's also marked volatile, because it will change in a way which is not predictable by the compiler (here: from a different thread.) */ /* t1 uses spin lock to wait for i to change from 0. */ static void *f1() { while (i==0) { /* do nothing - just keep checking over and over. */ } printf("i's value has changed to %d.\n", i); return; } static void *f2() { sleep(60); /* sleep for 60 seconds. */ i = 99; printf("t2 changing the value of i to %d.\n", i); return; } int main() { int x; pthread_t t1, t2; i = 0; /* set global int i to 0. */ x = pthread_create(&t1, NULL, f1, NULL); if (x != 0) { printf("pthread foo failed.\n"); } x = pthread_create(&t2, NULL, f2, NULL); if (x != 0) { printf("pthread bar failed.\n"); } pthread_join(t1, NULL); pthread_join(t2, NULL); printf("all pthreads finished.\n"); return 0; }
En un sistema UNIX, puede compilar este código con este comando:
$ cc spinlock.c -lpthread
En Linux, reemplace el compilador cc con el compilador gcc.