Created
March 18, 2025 07:52
-
-
Save ProfAndreaPollini/89168dfdf041020663bba9b24681602b to your computer and use it in GitHub Desktop.
simulazione casse supermercato
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import threading | |
import time | |
import random | |
nome_file_log = "esempio_log_competizione.txt" | |
mutex = threading.Lock() | |
def scrivi_log(nome_processo): | |
with mutex: | |
for i in range(3): # Ogni processo scrive 3 righe di log | |
messaggio_log = f"{nome_processo} - Riga {i+1} - Timestamp: {time.strftime('%H:%M:%S')}\n" | |
time.sleep(random.uniform(0.1, 0.3)) # Simula un po' di lavoro | |
with open(nome_file_log, "a") as file_log: # Apre il file in modalità append | |
file_log.write(messaggio_log) | |
print(f"{nome_processo}: Scritta riga {i+1}") | |
processi = ["Cassa-A", "Cassa-B", "Cassa-C","Cassa-D"] | |
threads_log = [] | |
print("Simulazione di scrittura su file SENZA PROTEZIONE:") | |
for processo in processi: | |
thread = threading.Thread(target=scrivi_log, args=(processo,)) | |
threads_log.append(thread) | |
for thread in threads_log: | |
thread.start() | |
for thread in threads_log: | |
thread.join() | |
print(f"\nContenuto del file di log '{nome_file_log}':") | |
with open(nome_file_log, "r") as file_log: | |
print(file_log.read()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment