Created
February 18, 2025 07:45
-
-
Save ProfAndreaPollini/96e28fbf6fa379282b83dd3d4e4fabc9 to your computer and use it in GitHub Desktop.
Esempio di utilizzo di lock con python e thread multipli
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 | |
contatore = 0 | |
occupata = False | |
lock = threading.Lock() | |
def incrementa_contatore(): | |
global contatore,occupata,lock | |
for _ in range(100000): | |
lock.acquire() | |
contatore += 1 | |
lock.release() | |
start_time = time.perf_counter() | |
threads = [] | |
for _ in range(10): | |
thread = threading.Thread(target=incrementa_contatore) | |
threads.append(thread) | |
#thread2 = threading.Thread(target=incrementa_contatore) | |
for i in range(10): | |
threads[i].start() | |
#thread2.start() | |
for i in range(10): | |
threads[i].join() | |
#thread2.join() | |
end_time = time.perf_counter() | |
print(f"Valore finale del contatore (senza protezione): {contatore}") | |
print(f"Tempo di esecuzione: {end_time - start_time:.6f} secondi") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment