Forks and Mutex
Forks and Mutex
import threading
counter = 0
def increment():
global counter
for _ in range(100000):
with lock: # Only one thread can enter this block at a time
counter += 1
# Create threads
t1 = threading.Thread(target=increment)
t2 = threading.Thread(target=increment)
# Start threads
t1.start()
t2.start()
t1.join()
t2.join()
This prevents the race condition and gives the correct final result: 200000.
import os
pid = os.fork()
if pid == 0:
print("Child Process")
else:
print("Parent Process")