Guest User

Ejemplo de threading

a guest
Mar 24th, 2012
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.22 KB | None | 0 0
  1. # -*- coding: cp1252 -*-
  2. import threading
  3. import time
  4.  
  5. class hilo1(threading.Thread):
  6.     def __init__(self):  
  7.         threading.Thread.__init__(self)  
  8.         self.valor=2.
  9.          
  10.     def run(self):
  11.         print "Soy el hilo que calcula.",
  12.         print "No volverás a saber de mí."
  13.         print
  14.         while True:
  15.             self.valor=self.valor+1/self.valor  # Calculamos algo
  16.             time.sleep(0.2)                     # y a dormir para no subir demasiado rápido.
  17.  
  18.             if self.valor>10: break             # Me canso y termino.
  19.            
  20.  
  21. class contador(threading.Thread):
  22.     def __init__(self):  
  23.         threading.Thread.__init__(self)  
  24.  
  25.     def run(self):
  26.         print "Soy el hilo contador."
  27.         while True:
  28.             time.sleep(1)
  29.             print "Ha pasado otro segundo.  ",
  30.             print h.valor                       # Accede al otro hilo y averigua ese valor.
  31.  
  32.             if h.valor>10: break                # Fin.
  33.  
  34.  
  35. h=hilo1()
  36. h.start()           # Lanza el cálculo.
  37.  
  38. time.sleep(0.1)     # Para evitar que los prints se mezclen.
  39.  
  40. t=contador()
  41. t.start()           # Lanza el contador.
  42. h.join()            # Espera a que termine de ejecutarse h.
  43.  
  44. print 'Fin'
Advertisement
Add Comment
Please, Sign In to add comment