Does the GIL make this program thread-safe in CPython as of Python 3.13 with-gil? /u/Mysterious-Rent7233 Python Education

import threading # Shared variable counter = 0 # Number of increments per thread increments_per_thread = 50000000 # Function to increment the counter def increment(): global counter for _ in range(increments_per_thread): # This is not thread-safe counter = counter + 1 # Number of threads num_threads = 50 # List to hold threads threads = [] # Create and start threads for _ in range(num_threads): thread = threading.Thread(target=increment) threads.append(thread) for thread in threads: thread.start() # Wait for all threads to complete for thread in threads: thread.join() # Expected result expected_result = num_threads * increments_per_thread # Print the results print(f"Expected counter value: {expected_result}") print(f"Actual counter value: {counter}") 

submitted by /u/Mysterious-Rent7233
[link] [comments]

​r/learnpython import threading # Shared variable counter = 0 # Number of increments per thread increments_per_thread = 50000000 # Function to increment the counter def increment(): global counter for _ in range(increments_per_thread): # This is not thread-safe counter = counter + 1 # Number of threads num_threads = 50 # List to hold threads threads = [] # Create and start threads for _ in range(num_threads): thread = threading.Thread(target=increment) threads.append(thread) for thread in threads: thread.start() # Wait for all threads to complete for thread in threads: thread.join() # Expected result expected_result = num_threads * increments_per_thread # Print the results print(f”Expected counter value: {expected_result}”) print(f”Actual counter value: {counter}”) submitted by /u/Mysterious-Rent7233 [link] [comments] 

import threading # Shared variable counter = 0 # Number of increments per thread increments_per_thread = 50000000 # Function to increment the counter def increment(): global counter for _ in range(increments_per_thread): # This is not thread-safe counter = counter + 1 # Number of threads num_threads = 50 # List to hold threads threads = [] # Create and start threads for _ in range(num_threads): thread = threading.Thread(target=increment) threads.append(thread) for thread in threads: thread.start() # Wait for all threads to complete for thread in threads: thread.join() # Expected result expected_result = num_threads * increments_per_thread # Print the results print(f"Expected counter value: {expected_result}") print(f"Actual counter value: {counter}") 

submitted by /u/Mysterious-Rent7233
[link] [comments] 

Leave a Reply

Your email address will not be published. Required fields are marked *