import threading
sem = threading.Semaphore()
def fun1():
while True:
sem.acquire()
print(1)
sem.release()
def fun2():
while True:
sem.acquire()
print(2)
sem.release()
t1 = threading.Thread(target=fun1)
t1.start()
t2 = threading.Thread(target=fun2)
t2.start()
However, the issue you're experiencing, where only "1" is being printed, is due to the threads acquiring and releasing the semaphore in quick succession. To ensure proper synchronization and alternate printing "1" and "2", you can modify the code as follows:
import threading
sem = threading.Semaphore(0) # Initialize the semaphore with a value of 0
def fun1():
while True:
print(1)
sem.release() # Release the semaphore to allow the other thread to acquire it
sem.acquire() # Acquire the semaphore to wait until the other thread releases it
def fun2():
while True:
sem.acquire() # Acquire the semaphore to wait until the other thread releases it
print(2)
sem.release() # Release the semaphore to allow the other thread to acquire it
t1 = threading.Thread(target=fun1)
t1.start()
t2 = threading.Thread(target=fun2)
t2.start()
In this code, the semaphore is initially set to 0. The first thread (fun1) starts by printing "1" and then releases the semaphore, allowing the second thread (fun2) to acquire it. The second thread then prints "2" and releases the semaphore, allowing the first thread to acquire it again. This creates a synchronized behavior where "1" and "2" are printed alternately by the two threads.