Files
live-campus-mcs-p-2027.2/Semaine_09/Threading_Process/main.py
T
gauvainboiche ce1f0e513a feat: Semaine 9
2026-05-15 16:24:56 +02:00

69 lines
1.8 KiB
Python

"""
IO-bound : le CPU ne fait rien, il attend. Requêtes API/DB/fichiers
CPU-bound : le CPU est sollicité
"""
import os, time
from threading import Thread, current_thread
from multiprocessing import Process, current_process
COUNT = 200000000
SLEEP = 10
def io_bound(sec):
pid = os.getpid()
thread_name = current_thread().name
process_name = current_process().name
print(f"{pid} - {process_name} - {thread_name} => Start sleeping...")
time.sleep(sec)
print(f"{pid} - {process_name} - {thread_name} => Stop sleeping...")
def cpu_bound(n):
pid = os.getpid()
thread_name = current_thread().name
process_name = current_process().name
print(f"{pid} - {process_name} - {thread_name} => Start counting...")
while n > 0:
n -= 1
print(f"{pid} - {process_name} - {thread_name} => Stop counting...")
if __name__ == "__main__":
start_time = time.perf_counter()
# io_bound(SLEEP)
# io_bound(SLEEP)
# t1 = Thread(target= io_bound, args= (SLEEP, ))
# t2 = Thread(target= io_bound, args= (SLEEP, ))
# t1.start()
# t2.start()
# t1.join()
# t2.join()
# cpu_bound(COUNT)
# cpu_bound(COUNT)
# t1 = Thread(target= cpu_bound, args= (COUNT, ))
# t2 = Thread(target= cpu_bound, args= (COUNT, ))
# t1.start()
# t2.start()
# t1.join()
# t2.join()
t1 = Process(target= cpu_bound, args= (COUNT, ))
t2 = Process(target= cpu_bound, args= (COUNT, ))
t1.start()
t2.start()
t1.join()
t2.join()
end_time = time.perf_counter()
print(f"Time taken in seconds - {end_time - start_time}")
"""
Tâches IO-bound => Threading
Tâches CPU-bound => Multiprocessing
IO-bound avec connexions simultanées => asyncio
"""