├── process ├── 1.-process.py ├── 10.-cola.py ├── 11.-race.py ├── 2.-finalizar.py ├── 3.-herencias.py ├── 4.-pool.py ├── 5.-modulo-processing.py ├── 6.-pool.py ├── 7.-maps.py ├── 8.-pipes.py └── 9.-manager.py └── threads ├── 1.-threads.py ├── 10.-join.py ├── 11.-demonio-example.py ├── 11.-demonios.py ├── 12.-clase-threading.py ├── 13.-clases.py ├── 14.-race_condition.py ├── 15.-rlock.py ├── 16.-events-example.py ├── 16.-events.py ├── 17.-queue.py ├── 18.-pool.py ├── 19.-contexto.py ├── 2.-multiples_threads.py ├── 20.-futuros_pools.py ├── 3.-logging.py ├── 4.-main.py ├── 5.-sleep.py ├── 6.-callbacks.py ├── 7.-timer.py ├── 8.-futuros.py ├── 9.-futures.py ├── Roboto ├── LICENSE.txt ├── Roboto-Black.ttf ├── Roboto-BlackItalic.ttf ├── Roboto-Bold.ttf ├── Roboto-BoldItalic.ttf ├── Roboto-Light.ttf ├── Roboto-LightItalic.ttf ├── Roboto-Medium.ttf ├── Roboto-MediumItalic.ttf ├── Roboto-Regular.ttf ├── Roboto-RegularItalic.ttf ├── Roboto-Thin.ttf └── Roboto-ThinItalic.ttf ├── guil.py └── producer_and_consumer.py /process/1.-process.py: -------------------------------------------------------------------------------- 1 | import os 2 | import time 3 | import logging 4 | import multiprocessing 5 | 6 | logging.basicConfig(level=logging.DEBUG, format='%(process)s %(processName)s %(message)s') 7 | 8 | def nuevo_proceso(mensaje): 9 | logging.info('Hola, soy un nuevo proceso') 10 | 11 | time.sleep(3) 12 | 13 | logging.info(mensaje) 14 | 15 | logging.info('Fin del proceso') 16 | 17 | if __name__ == '__main__': 18 | # args o kwargs 19 | process = multiprocessing.Process(target=nuevo_proceso, name='proceso-hijo', 20 | kwargs={'mensaje': 'Nuevo mensaje, desde un argumento!'}) 21 | process.start() 22 | 23 | process.join() 24 | 25 | logging.info('Hola, desde el proceso padre') 26 | -------------------------------------------------------------------------------- /process/10.-cola.py: -------------------------------------------------------------------------------- 1 | import time 2 | import logging 3 | import multiprocessing 4 | 5 | logging.basicConfig(level=logging.DEBUG, format='%(processName)s %(message)s') 6 | 7 | # Colas 8 | def get_elements(queue): 9 | while not queue.empty(): 10 | element = queue.get(block=True) 11 | logging.info(f'El elemento es: {element}') 12 | 13 | if __name__ == '__main__': 14 | manager = multiprocessing.Manager() 15 | queue = manager.Queue() 16 | 17 | for x in range(1, 21): 18 | queue.put(x) 19 | 20 | logging.info('La cola ya posee elementos!') 21 | 22 | process1 = multiprocessing.Process(target=get_elements, args=(queue, )) 23 | process2 = multiprocessing.Process(target=get_elements, args=(queue, )) 24 | process3 = multiprocessing.Process(target=get_elements, args=(queue, )) 25 | 26 | process1.start() 27 | process2.start() 28 | process3.start() 29 | 30 | process1.join() 31 | process2.join() 32 | process3.join() 33 | 34 | logging.info('Fin de los procesos!') 35 | -------------------------------------------------------------------------------- /process/11.-race.py: -------------------------------------------------------------------------------- 1 | import time 2 | import logging 3 | import multiprocessing 4 | 5 | logging.basicConfig(level=logging.DEBUG, format='%(processName)s %(message)s') 6 | 7 | def deposit(namespace, lock): 8 | for _ in range(1, 100000): 9 | 10 | lock.acquire() 11 | namespace.balance += 1 12 | lock.release() 13 | 14 | def withdraw(namespace, lock): 15 | for _ in range(1, 100000): 16 | with lock: 17 | namespace.balance -= 1 18 | 19 | if __name__ == '__main__': 20 | manager = multiprocessing.Manager() 21 | 22 | lock = manager.Lock() 23 | 24 | namespace = manager.Namespace() 25 | namespace.balance = 0 26 | 27 | proccess1 = multiprocessing.Process(target=deposit, args=(namespace, lock)) 28 | proccess2 = multiprocessing.Process(target=withdraw, args=(namespace, lock)) 29 | 30 | proccess1.start() 31 | proccess2.start() 32 | 33 | proccess1.join() 34 | proccess2.join() 35 | 36 | logging.info(f'Valor balance final es: {namespace.balance}') 37 | -------------------------------------------------------------------------------- /process/2.-finalizar.py: -------------------------------------------------------------------------------- 1 | import os 2 | import time 3 | import logging 4 | import multiprocessing 5 | 6 | logging.basicConfig(level=logging.DEBUG, format='%(message)s') 7 | 8 | def proceso_hijo(): 9 | logging.info('Hola, desde el procesos hijo!') 10 | 11 | time.sleep(2) 12 | 13 | logging.info('Fin del proceso hijo!') 14 | 15 | if __name__ == '__main__': 16 | process = multiprocessing.Process(target=proceso_hijo) 17 | process.start() 18 | 19 | time.sleep(5) 20 | 21 | if process.is_alive(): 22 | process.terminate() 23 | logging.info('Proceso hijo finalizado antes de tiempo') 24 | 25 | logging.info('Fin del programa!') 26 | -------------------------------------------------------------------------------- /process/3.-herencias.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import multiprocessing 3 | 4 | logging.basicConfig(level=logging.DEBUG, format='%(message)s') 5 | 6 | class ProcesoFacilito(multiprocessing.Process): 7 | def __init__(self, daemon, name): 8 | multiprocessing.Process.__init__(self, daemon=daemon, name=name) 9 | 10 | def run(self): 11 | logging.info('Este mensaje se crea en un nuevo proceso!') 12 | 13 | if __name__ == '__main__': 14 | proceso_facilito = ProcesoFacilito(False, 'proceso-facilito') 15 | proceso_facilito.start() 16 | -------------------------------------------------------------------------------- /process/4.-pool.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from concurrent.futures import ProcessPoolExecutor 3 | 4 | logging.basicConfig(level=logging.DEBUG, format='%(processName)s %(message)s') 5 | 6 | def is_even(number): 7 | return number % 2 == 0 8 | 9 | if __name__ == '__main__': 10 | with ProcessPoolExecutor(max_workers=2) as executor: 11 | 12 | future = executor.submit(is_even, 10) 13 | future.add_done_callback( 14 | lambda future: logging.info(f'El número es par? {future.result()}') 15 | ) 16 | 17 | future = executor.submit(is_even, 1895) 18 | future.add_done_callback( 19 | lambda future: logging.info(f'El número es par? {future.result()}') 20 | ) 21 | -------------------------------------------------------------------------------- /process/5.-modulo-processing.py: -------------------------------------------------------------------------------- 1 | import os 2 | import time 3 | import logging 4 | import multiprocessing 5 | 6 | logging.basicConfig(level=logging.DEBUG, format='%(message)s') 7 | 8 | if __name__ == '__main__': 9 | current_process = multiprocessing.current_process() 10 | pid = current_process.pid 11 | name = current_process.name 12 | 13 | logging.info(f'El proceso actual es: {current_process}') 14 | logging.info(f'El id del proceso es: {pid}') 15 | logging.info(f'El nombre del proceso es: {name}') 16 | -------------------------------------------------------------------------------- /process/6.-pool.py: -------------------------------------------------------------------------------- 1 | import time 2 | import logging 3 | # from concurrent.futures import ProcessPoolExecutor 4 | from multiprocessing import Pool 5 | 6 | logging.basicConfig(level=logging.DEBUG, format='%(processName)s %(message)s') 7 | 8 | def is_even(number): 9 | time.sleep(5) 10 | return number % 2 == 0 11 | 12 | if __name__ == '__main__': 13 | with Pool(processes=2) as executor: 14 | 15 | apply_result = executor.apply_async(is_even, args=(10, )) 16 | 17 | logging.info(apply_result) 18 | 19 | logging.info('Vamos a esperar hasta que apply_result posea un valor') 20 | 21 | apply_result.wait(timeout=2) 22 | 23 | logging.info('Apply_result ha finalizado') 24 | 25 | logging.info(f'El resultado es: {apply_result.get(timeout=1)}') 26 | 27 | logging.info(f'Fin del programa') 28 | -------------------------------------------------------------------------------- /process/7.-maps.py: -------------------------------------------------------------------------------- 1 | import time 2 | import logging 3 | from multiprocessing import Pool 4 | 5 | logging.basicConfig(level=logging.DEBUG, format='%(processName)s %(message)s') 6 | 7 | def is_even(number): 8 | time.sleep(1) 9 | return number % 2 == 0 10 | 11 | def show_result(results): 12 | logging.info(f'El resultado es: {results}') 13 | 14 | if __name__ == '__main__': 15 | with Pool(processes=2) as executor: 16 | numbers = [ number for number in range(1, 11)] 17 | 18 | for element in executor.imap_unordered(is_even, numbers): # yield 19 | logging.info(element) 20 | -------------------------------------------------------------------------------- /process/8.-pipes.py: -------------------------------------------------------------------------------- 1 | import time 2 | import logging 3 | import multiprocessing 4 | 5 | logging.basicConfig(level=logging.DEBUG, format='%(processName)s %(message)s') 6 | 7 | # PIPES 8 | # Publisher 9 | # Subscriber 10 | 11 | class Publisher(multiprocessing.Process): 12 | def __init__(self, connection): 13 | self.connection = connection 14 | multiprocessing.Process.__init__(self) 15 | 16 | def run(self): 17 | logging.info('Hola, nos encontramos en el proceso Publisher') 18 | 19 | for x in range(20): 20 | self.connection.send(f'Hola, desde el proceso publisher, con el valor {x}') 21 | 22 | time.sleep(0.5) 23 | 24 | self.connection.send(None) 25 | self.connection.close() 26 | 27 | logging.info('Conexión cerrada para publisher') 28 | 29 | class Subscriber(multiprocessing.Process): 30 | def __init__(self, connection): 31 | self.is_alive = True 32 | self.connection = connection 33 | multiprocessing.Process.__init__(self) 34 | 35 | def run(self): 36 | logging.info('Hola, nos encontramos en el proceso subscriber') 37 | 38 | while self.is_alive: 39 | result = self.connection.recv() 40 | 41 | self.is_alive = result is not None 42 | 43 | logging.info(result) 44 | else: 45 | self.connection.close() 46 | logging.info('Conexión cerrada para subscriber') 47 | 48 | if __name__ == '__main__': 49 | connection1, connection2 = multiprocessing.Pipe() 50 | 51 | publisher = Publisher(connection1) 52 | subscriber = Subscriber(connection2) 53 | 54 | publisher.start() 55 | subscriber.start() 56 | -------------------------------------------------------------------------------- /process/9.-manager.py: -------------------------------------------------------------------------------- 1 | import time 2 | import logging 3 | import multiprocessing 4 | 5 | logging.basicConfig(level=logging.DEBUG, format='%(processName)s %(message)s') 6 | 7 | # Manager -> Namespace -> Contexto 8 | def get_valor(namespace): 9 | while namespace.codigofacilito is None: 10 | time.sleep(0.5) 11 | logging.info('codigofacilito no posee valor alguno!') 12 | else: 13 | logging.info(namespace.codigofacilito) 14 | logging.info(namespace.prueba_de_nueva_variable) 15 | 16 | def set_valor(namespace): 17 | time.sleep(4) 18 | namespace.codigofacilito = 'Una escuela de educación en línea!' 19 | 20 | if __name__ == '__main__': 21 | manager = multiprocessing.Manager() 22 | namespace = manager.Namespace() 23 | 24 | namespace.codigofacilito = None 25 | namespace.prueba_de_nueva_variable = True 26 | 27 | process1 = multiprocessing.Process(target=get_valor, args=(namespace, )) 28 | process2 = multiprocessing.Process(target=set_valor, args=(namespace, )) 29 | 30 | process1.start() 31 | process2.start() 32 | 33 | process1.join() 34 | process2.join() 35 | -------------------------------------------------------------------------------- /threads/1.-threads.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import threading 3 | 4 | def get_name(): 5 | response = requests.get('https://randomuser.me/api/') 6 | if response.status_code == 200: #OK 7 | 8 | results = response.json().get('results') 9 | name = results[0].get('name').get('first') 10 | 11 | print(name) 12 | 13 | if __name__ == '__main__': 14 | # Concurrente 15 | for _ in range(0, 20): 16 | thread = threading.Thread(target=get_name) 17 | thread.start() 18 | -------------------------------------------------------------------------------- /threads/10.-join.py: -------------------------------------------------------------------------------- 1 | import time 2 | import logging 3 | import threading 4 | 5 | logging.basicConfig(level=logging.DEBUG, format='%(message)s') 6 | 7 | def conexion_base_datos(): 8 | logging.info('Comenzamos la conexión a la base de datos') 9 | time.sleep(2) 10 | 11 | def consulta_servidor_web(): 12 | logging.info('Comenzamos la consulta al servidor') 13 | time.sleep(2.5) 14 | 15 | if __name__ == '__main__': 16 | thread1 = threading.Thread(target=conexion_base_datos) 17 | thread2 = threading.Thread(target=consulta_servidor_web) 18 | 19 | thread1.start() 20 | thread2.start() 21 | 22 | thread1.join() 23 | thread2.join() 24 | 25 | logging.info('Final del programa, los threads han finalizado') 26 | -------------------------------------------------------------------------------- /threads/11.-demonio-example.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import time 3 | import pygame 4 | import requests 5 | import threading 6 | 7 | pygame.init() 8 | 9 | width = 600 10 | height = 600 11 | 12 | TEXT = 'Hola' 13 | 14 | def get_btc_price(url='https://api.bitso.com/v3/ticker/'): 15 | global TEXT 16 | 17 | while True: 18 | response = requests.get(url) 19 | 20 | if response.status_code == 200: 21 | payload = response.json().get('payload')[0] 22 | price = payload.get('last') 23 | 24 | TEXT = f'El precio actual del BTC es: ${price} MXN' 25 | 26 | time.sleep(1) 27 | 28 | thread = threading.Thread(target=get_btc_price, daemon=True) 29 | thread.start() 30 | 31 | surface = pygame.display.set_mode( (width, height) ) 32 | pygame.display.set_caption('Texto') 33 | 34 | white = (255, 255, 255) 35 | red = (115, 38, 80) 36 | black = (0, 0, 0) 37 | 38 | font = pygame.font.Font('Roboto/Roboto-Thin.ttf', 24) 39 | 40 | while True: 41 | 42 | text = font.render(TEXT, True, black) 43 | rect = text.get_rect() 44 | rect.center = (width // 2, height//2) 45 | 46 | surface.fill(white) 47 | 48 | for event in pygame.event.get(): 49 | if event.type == pygame.QUIT: 50 | pygame.quit() 51 | sys.exit() 52 | 53 | surface.blit(text, rect) 54 | 55 | pygame.display.update() 56 | -------------------------------------------------------------------------------- /threads/11.-demonios.py: -------------------------------------------------------------------------------- 1 | import time 2 | import logging 3 | import requests 4 | import threading 5 | 6 | logging.basicConfig(level=logging.DEBUG, format='%(message)s') 7 | 8 | def thread(): 9 | logging.info('Hola, soy un thread normal') 10 | time.sleep(2) 11 | logging.info('El programa finaliza cuando YO finalizo!') 12 | 13 | def daemon_thread(): 14 | while True: 15 | logging.info('Nos ejecutamos en segundo plano, en background!') 16 | time.sleep(0.5) 17 | 18 | if __name__ == '__main__': 19 | thread = threading.Thread(target=daemon_thread, daemon=True) 20 | thread.start() 21 | 22 | input('Presiona una tecla para finalizar el thread principal ') 23 | -------------------------------------------------------------------------------- /threads/12.-clase-threading.py: -------------------------------------------------------------------------------- 1 | import time 2 | import logging 3 | import threading 4 | 5 | logging.basicConfig(level=logging.DEBUG, format='%(message)s') 6 | 7 | def nueva_tarea(): 8 | current_thread = threading.current_thread() 9 | name = current_thread.getName() 10 | id = threading.get_ident() 11 | 12 | logging.info(f'El Thread actual es: {current_thread} y su nombre es: {name}') 13 | logging.info(f'El id actual es: {id}') 14 | 15 | if __name__ == '__main__': 16 | thread1 = threading.Thread(target=nueva_tarea, name='thread-facilito') 17 | thread1.start() 18 | 19 | #logging.info(f'Los threads vivos son: {threading.enumerate()}') 20 | for thread in threading.enumerate(): 21 | if thread == threading.main_thread(): 22 | logging.info('Nos encontramos en el thread principal!') 23 | 24 | logging.info(thread) 25 | -------------------------------------------------------------------------------- /threads/13.-clases.py: -------------------------------------------------------------------------------- 1 | import time 2 | import logging 3 | import threading 4 | 5 | logging.basicConfig(level=logging.DEBUG, format='%(threadName)s: %(message)s') 6 | 7 | class ThreadFacilito(threading.Thread): 8 | def __init__(self, name, daemon): 9 | threading.Thread.__init__(self, name=name, daemon=daemon) 10 | 11 | def run(self): 12 | while True: 13 | logging.info('Aquí debemos colocar todas las tareas que queremos se ejecuten de forma concurrente!') 14 | time.sleep(1) 15 | 16 | if __name__ == '__main__': 17 | thread = ThreadFacilito('Thread-Facilito', True) 18 | thread.start() 19 | 20 | time.sleep(3) 21 | logging.info('FIN del programa!') 22 | -------------------------------------------------------------------------------- /threads/14.-race_condition.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import threading 3 | 4 | logging.basicConfig(level=logging.DEBUG, format='%(threadName)s: %(message)s') 5 | 6 | BALANCE = 0 7 | 8 | lock = threading.Lock() 9 | 10 | def depositos(): 11 | global BALANCE 12 | 13 | for _ in range(0, 1000000): 14 | try: 15 | lock.acquire() 16 | BALANCE += 1 17 | finally: 18 | lock.release() 19 | 20 | def retiros(): 21 | global BALANCE 22 | 23 | for _ in range(0, 1000000): 24 | with lock: 25 | BALANCE -= 1 # Sección critica 26 | 27 | if __name__ == '__main__': 28 | thread1 = threading.Thread(target=depositos) 29 | thread2 = threading.Thread(target=retiros) 30 | 31 | thread1.start() 32 | thread2.start() 33 | 34 | thread1.join() 35 | thread2.join() 36 | 37 | logging.info(f'El valor final del balance es: {BALANCE}') 38 | -------------------------------------------------------------------------------- /threads/15.-rlock.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import threading 3 | 4 | logging.basicConfig(level=logging.DEBUG, format='%(threadName)s: %(message)s') 5 | 6 | BALANCE = 100 7 | 8 | # Lock y RLock 9 | lock = threading.RLock() 10 | 11 | if __name__ == '__main__': 12 | 13 | lock.acquire() # Estado: Ocupado 14 | 15 | lock.acquire() # A la espera de que sea liberado 16 | 17 | BALANCE -= 10 18 | 19 | lock.release() 20 | 21 | lock.release() 22 | 23 | logging.info(f'Finalizamos el thread principal con el balance: {BALANCE}') 24 | -------------------------------------------------------------------------------- /threads/16.-events-example.py: -------------------------------------------------------------------------------- 1 | import time 2 | import logging 3 | import requests 4 | import threading 5 | 6 | logging.basicConfig(level=logging.DEBUG, format='%(threadName)s: %(message)s') 7 | 8 | user = dict() 9 | 10 | def generate_request(url, event): 11 | global user 12 | 13 | response = requests.get(url) 14 | 15 | if response.status_code == 200: 16 | response_json = response.json() 17 | 18 | user = response_json.get('results')[0] 19 | 20 | event.set() 21 | 22 | def show_user_name(event): 23 | 24 | event.wait() 25 | 26 | name = user.get('name').get('first') 27 | 28 | logging.info(f'El nombre del usuario es: {name}') 29 | 30 | if __name__ == '__main__': 31 | event = threading.Event() 32 | 33 | thread1 = threading.Thread(target=generate_request, args=('https://randomuser.me/api', event)) 34 | thread2 = threading.Thread(target=show_user_name, args=(event, )) 35 | 36 | thread1.start() 37 | thread2.start() 38 | -------------------------------------------------------------------------------- /threads/16.-events.py: -------------------------------------------------------------------------------- 1 | import time 2 | import logging 3 | import threading 4 | 5 | logging.basicConfig(level=logging.DEBUG, format='%(threadName)s: %(message)s') 6 | 7 | def thread_1(event): 8 | logging.info('Estoy a la espera de la señal!') 9 | 10 | event.wait() 11 | 12 | logging.info('La señal fue dada, la bandera es True') 13 | 14 | def thread_2(event): 15 | 16 | while not event.is_set(): 17 | logging.info('A la espera de la señal') 18 | time.sleep(0.5) 19 | 20 | if __name__ == '__main__': 21 | 22 | event = threading.Event() 23 | # Bandera = True o False* 24 | 25 | thread1 = threading.Thread(target=thread_1, args=(event, )) 26 | thread2 = threading.Thread(target=thread_2, args=(event, )) 27 | 28 | thread1.start() 29 | thread2.start() 30 | 31 | time.sleep(3) 32 | 33 | event.set() # Estaremos dando la señal 34 | 35 | event.clear() 36 | -------------------------------------------------------------------------------- /threads/17.-queue.py: -------------------------------------------------------------------------------- 1 | import time 2 | import queue 3 | import logging 4 | import threading 5 | 6 | logging.basicConfig(level=logging.DEBUG, format='%(threadName)s: %(message)s') 7 | 8 | def show_elements(): 9 | while not queue.empty(): 10 | item = queue.get() 11 | 12 | logging.info(f'El elemento es: {item}') 13 | 14 | queue.task_done() 15 | 16 | time.sleep(0.5) 17 | 18 | if __name__ == '__main__': 19 | queue = queue.Queue() #FIFO 20 | 21 | for val in range(1, 20): 22 | queue.put(val) 23 | 24 | logging.info('La cola ya posee elementos!') 25 | 26 | for _ in range(4): 27 | thread = threading.Thread(target=show_elements) 28 | thread.start() 29 | -------------------------------------------------------------------------------- /threads/18.-pool.py: -------------------------------------------------------------------------------- 1 | import time 2 | import logging 3 | import threading 4 | 5 | from concurrent.futures import ThreadPoolExecutor 6 | 7 | logging.basicConfig(level=logging.DEBUG, format='%(threadName)s: %(message)s',) 8 | 9 | def math_operation(number1, number2): 10 | time.sleep(1) 11 | 12 | result = number1 + number2 13 | logging.info(f'Resultado de {number1} + {number2} = {result}') 14 | 15 | if __name__ == '__main__': 16 | executor = ThreadPoolExecutor(max_workers=3, thread_name_prefix='facilitos') 17 | 18 | executor.submit(math_operation, 10, 20) 19 | executor.submit(math_operation, 40, 50) 20 | 21 | executor.submit(math_operation, 100, 200) 22 | executor.submit(math_operation, 60, 70) 23 | -------------------------------------------------------------------------------- /threads/19.-contexto.py: -------------------------------------------------------------------------------- 1 | import time 2 | import logging 3 | import threading 4 | 5 | from concurrent.futures import ThreadPoolExecutor 6 | 7 | logging.basicConfig(level=logging.DEBUG, format='%(threadName)s: %(message)s',) 8 | 9 | def math_operation(number1, number2): 10 | time.sleep(1) 11 | 12 | result = number1 + number2 13 | logging.info(f'Resultado de {number1} + {number2} = {result}') 14 | 15 | if __name__ == '__main__': 16 | with ThreadPoolExecutor(max_workers=3, thread_name_prefix='facilitos') as executor: 17 | 18 | executor.submit(math_operation, 10, 20) 19 | executor.submit(math_operation, 40, 50) 20 | executor.submit(math_operation, 100, 200) 21 | 22 | executor.submit(math_operation, 60, 70) 23 | 24 | 25 | -------------------------------------------------------------------------------- /threads/2.-multiples_threads.py: -------------------------------------------------------------------------------- 1 | import threading 2 | 3 | def executor_a(id=0): 4 | for x in range(0, 10): 5 | print(f'Hola, soy el Thread {id} iteración {x}') 6 | 7 | def executor_b(id=0): 8 | for x in range(0, 10): 9 | print(f'Hola, soy el Thread {id} iteración {x}') 10 | 11 | def executor_c(id=0): 12 | for x in range(0, 10): 13 | print(f'Hola, soy el Thread {id} iteración {x}') 14 | 15 | thread_a = threading.Thread(target=executor_a, args=[1]) 16 | thread_b = threading.Thread(target=executor_b, args=(2,)) 17 | thread_c = threading.Thread(target=executor_c, kwargs={'id': 3}) 18 | 19 | thread_a.start() 20 | thread_b.start() 21 | thread_c.start() 22 | -------------------------------------------------------------------------------- /threads/20.-futuros_pools.py: -------------------------------------------------------------------------------- 1 | import time 2 | import logging 3 | import requests 4 | import threading 5 | 6 | from concurrent.futures import as_completed 7 | from concurrent.futures import ThreadPoolExecutor 8 | 9 | logging.basicConfig(level=logging.DEBUG, format='%(threadName)s: %(message)s',) 10 | 11 | URLS = [ 12 | 'https://codigofacilito.com/', 13 | 'https://twitter.com/home', 14 | 'https://www.google.com/', 15 | 'https://es.stackoverflow.com/', 16 | 'https://stackoverflow.com/', 17 | 'https://about.gitlab.com/', 18 | 'https://github.com/', 19 | 'https://www.youtube.com/' 20 | ] 21 | 22 | def generate_request(url): 23 | return requests.get(url) 24 | 25 | def check_status_code(response, url): 26 | logging.info(f'La respuesta del servidor {url} es: {response.status_code}') 27 | 28 | if __name__ == '__main__': 29 | with ThreadPoolExecutor(max_workers=2) as executor: 30 | 31 | results = executor.map(generate_request, URLS) 32 | 33 | for url, response in zip(URLS, results): 34 | if response.status_code == 200: 35 | check_status_code(response, url) 36 | -------------------------------------------------------------------------------- /threads/3.-logging.py: -------------------------------------------------------------------------------- 1 | import logging 2 | 3 | # Debug (10), Info (20), Warning (30), Error (40), Critical (50) 4 | 5 | #logging 6 | 7 | logging.basicConfig( 8 | level=logging.DEBUG,#10 9 | format='%(message)s - %(processName)s', 10 | #datefmt='%H:%M:%S', 11 | #filename='messages.txt' 12 | ) 13 | 14 | def mis_mensajes(): 15 | logging.debug('Este es un mensaje de tipo Debug') 16 | logging.info('Este es un mensaje de tipo Info') 17 | logging.warning('Este es un mensaje de tipo Warning') 18 | logging.error('Este es un mensaje de tipo Error') 19 | logging.critical('Este es un mensaje de tipo Critical') 20 | 21 | if __name__ == '__main__': 22 | mis_mensajes() 23 | -------------------------------------------------------------------------------- /threads/4.-main.py: -------------------------------------------------------------------------------- 1 | import logging 2 | 3 | logging.basicConfig( 4 | level=logging.DEBUG, 5 | format='%(thread)s %(threadName)s : %(message)s' 6 | ) 7 | 8 | if __name__ == '__main__': 9 | logging.info('Hola, me encuentro en el thread principal!') 10 | 11 | -------------------------------------------------------------------------------- /threads/5.-sleep.py: -------------------------------------------------------------------------------- 1 | import time 2 | import logging 3 | import threading 4 | 5 | #sleep(segundos) 6 | 7 | logging.basicConfig( 8 | level=logging.DEBUG, 9 | format='%(message)s' 10 | ) 11 | 12 | if __name__ == '__main__': 13 | contador = 0 14 | 15 | while True: 16 | time.sleep(1) 17 | contador += 1 18 | logging.info(f'Tiempo transcurrido: {contador} segundos') 19 | -------------------------------------------------------------------------------- /threads/6.-callbacks.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import requests 3 | import threading 4 | 5 | logging.basicConfig(level=logging.DEBUG, format='%(message)s') 6 | 7 | def get_pokemon_name(response_json): 8 | name = response_json.get('forms')[0].get('name') 9 | logging.info(f'El nombre del pokemon es : {name}') 10 | 11 | def get_name_random(response_json): 12 | name = response_json.get('results')[0].get('name').get('first') 13 | logging.info(f'El nombre del usuario es : {name}') 14 | 15 | def error(): 16 | logging.error('No es posible completar la operación') 17 | 18 | # Hollywood 19 | def generate_request(url, success_callback, error_callback): 20 | response = requests.get(url) 21 | 22 | if response.status_code == 200: 23 | success_callback(response.json()) 24 | else: 25 | error_callback() 26 | 27 | if __name__ == '__main__': 28 | thread1 = threading.Thread(target=generate_request, kwargs={'url': 'https://pokeapi.co/api/v2/pokemon/1/', 29 | 'success_callback': get_pokemon_name, 30 | 'error_callback': error 31 | }) 32 | thread1.start() 33 | 34 | thread2 = threading.Thread(target=generate_request, kwargs={'url': 'https://randomuser.me/api', 35 | 'success_callback': get_name_random, 36 | 'error_callback': error 37 | }) 38 | thread2.start() 39 | -------------------------------------------------------------------------------- /threads/7.-timer.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import threading 3 | 4 | logging.basicConfig(level=logging.DEBUG, format='%(message)s') 5 | 6 | # Timer 7 | def callback(): 8 | logging.info('Hola, soy un callback que no ejecuta de forma inmediata') 9 | 10 | if __name__ == '__main__': 11 | thread = threading.Timer(3, callback) 12 | thread.start() 13 | 14 | logging.info('Hola, soy el thread principal') 15 | logging.info('Estamos a la espera de la ejecución del callback') 16 | -------------------------------------------------------------------------------- /threads/8.-futuros.py: -------------------------------------------------------------------------------- 1 | import time 2 | import logging 3 | import threading 4 | 5 | from concurrent.futures import Future 6 | 7 | logging.basicConfig(level=logging.DEBUG, format='%(message)s') 8 | 9 | # Futures = Abstracción de un resultado 10 | # Javascript = Promesas 11 | 12 | def callback_future(future): 13 | logging.info('Hola, soy un callback que se ejecuta hasta que el futuro posea un valor!') 14 | logging.info(f'El futuro es: {future.result()}') 15 | 16 | if __name__ == '__main__': 17 | future = Future() 18 | future.add_done_callback(callback_future) 19 | future.add_done_callback( 20 | lambda future: logging.info('Hola, soy una lambda!') 21 | ) 22 | 23 | logging.info('Comenzamos una tarea muy compleja!!!') 24 | 25 | time.sleep(2) 26 | 27 | logging.info('Terminamos la tarea compleja') 28 | 29 | logging.info('Vamos asignar un valor al futuro') 30 | 31 | future.set_result('CodigoFacilito') 32 | 33 | logging.info('El futuro ya posee un valor') 34 | -------------------------------------------------------------------------------- /threads/9.-futures.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import requests 3 | import threading 4 | from concurrent.futures import Future 5 | 6 | logging.basicConfig(level=logging.DEBUG, format='%(message)s') 7 | 8 | def show_pokemon_name(response): 9 | if response.status_code == 200: 10 | response_json = response.json() 11 | name = response_json.get('forms')[0].get('name') 12 | 13 | logging.info(f'El nombre del pokemon es {name}') 14 | 15 | def generate_request(url): 16 | future = Future() 17 | 18 | thread = threading.Thread(target=( 19 | lambda: future.set_result(requests.get(url)) 20 | )) 21 | thread.start() 22 | 23 | return future 24 | 25 | if __name__ == '__main__': 26 | future = generate_request('https://pokeapi.co/api/v2/pokemon/1/') 27 | future.add_done_callback( 28 | lambda future: show_pokemon_name(future.result()) 29 | ) 30 | 31 | while not future.done(): 32 | logging.info('A la espera de un resultado') 33 | else: 34 | logging.info('Terminamos el programa!') 35 | -------------------------------------------------------------------------------- /threads/Roboto/LICENSE.txt: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /threads/Roboto/Roboto-Black.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codigofacilito/python-concurrente/01255803dad5170fc73311b419a4ab5c27caa894/threads/Roboto/Roboto-Black.ttf -------------------------------------------------------------------------------- /threads/Roboto/Roboto-BlackItalic.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codigofacilito/python-concurrente/01255803dad5170fc73311b419a4ab5c27caa894/threads/Roboto/Roboto-BlackItalic.ttf -------------------------------------------------------------------------------- /threads/Roboto/Roboto-Bold.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codigofacilito/python-concurrente/01255803dad5170fc73311b419a4ab5c27caa894/threads/Roboto/Roboto-Bold.ttf -------------------------------------------------------------------------------- /threads/Roboto/Roboto-BoldItalic.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codigofacilito/python-concurrente/01255803dad5170fc73311b419a4ab5c27caa894/threads/Roboto/Roboto-BoldItalic.ttf -------------------------------------------------------------------------------- /threads/Roboto/Roboto-Light.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codigofacilito/python-concurrente/01255803dad5170fc73311b419a4ab5c27caa894/threads/Roboto/Roboto-Light.ttf -------------------------------------------------------------------------------- /threads/Roboto/Roboto-LightItalic.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codigofacilito/python-concurrente/01255803dad5170fc73311b419a4ab5c27caa894/threads/Roboto/Roboto-LightItalic.ttf -------------------------------------------------------------------------------- /threads/Roboto/Roboto-Medium.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codigofacilito/python-concurrente/01255803dad5170fc73311b419a4ab5c27caa894/threads/Roboto/Roboto-Medium.ttf -------------------------------------------------------------------------------- /threads/Roboto/Roboto-MediumItalic.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codigofacilito/python-concurrente/01255803dad5170fc73311b419a4ab5c27caa894/threads/Roboto/Roboto-MediumItalic.ttf -------------------------------------------------------------------------------- /threads/Roboto/Roboto-Regular.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codigofacilito/python-concurrente/01255803dad5170fc73311b419a4ab5c27caa894/threads/Roboto/Roboto-Regular.ttf -------------------------------------------------------------------------------- /threads/Roboto/Roboto-RegularItalic.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codigofacilito/python-concurrente/01255803dad5170fc73311b419a4ab5c27caa894/threads/Roboto/Roboto-RegularItalic.ttf -------------------------------------------------------------------------------- /threads/Roboto/Roboto-Thin.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codigofacilito/python-concurrente/01255803dad5170fc73311b419a4ab5c27caa894/threads/Roboto/Roboto-Thin.ttf -------------------------------------------------------------------------------- /threads/Roboto/Roboto-ThinItalic.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codigofacilito/python-concurrente/01255803dad5170fc73311b419a4ab5c27caa894/threads/Roboto/Roboto-ThinItalic.ttf -------------------------------------------------------------------------------- /threads/guil.py: -------------------------------------------------------------------------------- 1 | import time 2 | import threading 3 | import multiprocessing 4 | 5 | def countdown(number): 6 | while number > 0: 7 | number -=1 8 | 9 | if __name__ == '__main__': 10 | start = time.time() 11 | 12 | count = 100000000 13 | 14 | t1 = multiprocessing.Process(target=countdown, args=(count,)) 15 | t2 = multiprocessing.Process(target=countdown, args=(count,)) 16 | 17 | t1.start() 18 | t2.start() 19 | 20 | t1.join() 21 | t2.join() 22 | 23 | print(f'Tiempo transcurrido {time.time() - start }') 24 | -------------------------------------------------------------------------------- /threads/producer_and_consumer.py: -------------------------------------------------------------------------------- 1 | import time 2 | import queue 3 | import random 4 | import logging 5 | import threading 6 | 7 | logging.basicConfig(level=logging.DEBUG, format='%(threadName)s: %(message)s',) 8 | 9 | """ 10 | Problema productor-consumidor 11 | 12 | El programa describe dos procesos, productor y consumidor, 13 | ambos comparten un buffer de tamaño finito. 14 | La tarea del productor es generar un producto, almacenarlo y comenzar nuevamente; 15 | mientras que el consumidor toma (simultáneamente) productos uno a uno. 16 | El problema consiste en que el productor no añada más productos que la capacidad del buffer 17 | y que el consumidor no intente tomar un producto si el buffer está vacío. 18 | """ 19 | 20 | queue = queue.Queue(maxsize=10) 21 | 22 | def producer(): 23 | while True: 24 | if not queue.full(): 25 | item = random.randint(1, 10) 26 | queue.put(item) 27 | 28 | logging.info(f'Nuevo elemento dentro de la cola {item}') 29 | 30 | time_to_sleep = random.randint(1, 3) 31 | time.sleep(time_to_sleep) 32 | 33 | def consumer(): 34 | while True: 35 | if not queue.empty(): 36 | item = queue.get() 37 | queue.task_done() 38 | 39 | logging.info(f'Nuevo elemento obtenido {item}') 40 | 41 | time_to_sleep = random.randint(1, 3) 42 | time.sleep(time_to_sleep) 43 | 44 | if __name__ == '__main__': 45 | thread_producer = threading.Thread(target=producer) 46 | thread_consumer = threading.Thread(target=consumer) 47 | 48 | thread_producer.start() 49 | thread_consumer.start() 50 | --------------------------------------------------------------------------------