程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python simulates the dining problem of philosophers

編輯:Python

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()

 


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved