Apuntes_Python/02_conceptos/16_multithreading/b_queue_threading.py
2022-12-24 22:41:20 -03:00

75 lines
1.6 KiB
Python
Executable File

"""
Queue (cola) es usado como metodo de seguridad en procesos e hilos
para entornos de intercambio de datos. Sigue los principios FIFO.
"""
from threading import Thread, Lock, current_thread
from queue import Queue
import time
def worker(q):
while True:
valor = q.get()
# procesando...
with lock:
print(f'{current_thread().name} tiene valor {valor}')
q.task_done()
if __name__ == "__main__":
q = Queue()
# q.put(1)
# q.put(2)
# q.put(3)
# 3 2 1 -->
# first = q.get()
# print(first)
# q.not_empty() # retorna True si la cola esta vacia
# q.task_done() # avisa que esta tarea esta liberada
# q.join() # bloqua el hilo principal hasta q se complete este hilo
lock = Lock()
num_hilos = 10
for i in range(num_hilos):
hilo = Thread(target=worker, args=(q,))
# 'daemon thread' 'demoniza' el hilo.
# Lo termina cuando termina el hilo principal
hilo.daemon=True
hilo.start()
# llenar cola con elementos
for i in range(1, 21):
q.put(i)
q.join()
print('Fin Main')
"""
Thread-1 tiene valor 1
Thread-3 tiene valor 2
Thread-4 tiene valor 3
Thread-5 tiene valor 4
Thread-6 tiene valor 5
Thread-8 tiene valor 6
Thread-7 tiene valor 7
Thread-2 tiene valor 8
Thread-9 tiene valor 9
Thread-10 tiene valor 10
Thread-1 tiene valor 11
Thread-3 tiene valor 12
Thread-4 tiene valor 13
Thread-5 tiene valor 14
Thread-6 tiene valor 15
Thread-8 tiene valor 16
Thread-7 tiene valor 17
Thread-2 tiene valor 18
Thread-9 tiene valor 19
Thread-10 tiene valor 20
Fin Main
"""