There are two philosophers sitting on the table , There are two chopsticks on the table , The numbers are a and b, Only at the same time a、b A philosopher can only eat with two chopsticks , If chopsticks a By philosophers 1 The number has been snatched , chopsticks b By philosophers 2 The number has been snatched , At this time, both philosophers want to get the chopsticks in each other's hands and go to have a bite of rice , But they are not willing to take the initiative to put down their chopsticks to each other , At this point, I entered a long wait for the other party to release what I want “ resources ” The process of , This creates a deadlock .
import threading
import time
# Create two locks
lock_a=threading.Lock()
lock_b=threading.Lock()
def philosopher_a():
for i in range(99):
# locked
lock_a.acquire()
print(' philosopher a to lock_a Lock , Grab the chopsticks a')
lock_b.acquire()
print(f' philosopher a to lock_b Lock , Grab the chopsticks b,ab Two chopsticks in hand , Eat the first {i+1} Oral rice ')
# Unlock
lock_a.release()
print(' philosopher a to lock_a Unlock , The chopsticks were released a')
lock_b.release()
print(' philosopher a to lock_b Unlock , The chopsticks were released b')
# time.sleep(0.5)
def philosopher_b():
for i in range(99):
# locked
lock_b.acquire()
print(' philosopher b to lock_b Lock , Grab the chopsticks b')
lock_a.acquire()
print(f' philosopher b to lock_a Lock , Grab the chopsticks a,ab Two chopsticks in hand , Eat the first {i+1} Oral rice ')
# Unlock
lock_b.release()
print(' philosopher b to lock_b Unlock , The chopsticks were released b')
lock_a.release()
print(' philosopher b to lock_a Unlock , The chopsticks were released a')
# time.sleep(0.5)
if __name__ == '__main__':
t1=threading.Thread(target=philosopher_a)
t2=threading.Thread(target=philosopher_b)
t1.start()
t2.start()