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

[Master Wus Python bakery] day 4

編輯:Python

Preface : Master Wu, who can only stay at home on the national day, is very boring , Decided to open a Python The bakery passed the time . Every day after that , Master Wu will use a piece of code to simply realize the function of selling bread , And solve the problems exposed the day before .

Yesterday the baker complained that he was too tired to work alone , Master Wu asked two more masters to help .

""" Master Wu, please have two more python Baker , The work seems a lot easier ."""
import time
import threading
TOTAL = 0
END_FLAG = False
PRODUCER_NUM = 3
def producer(lock):
""" Making bread ."""
num = 0
global TOTAL
while True:
time.sleep(1)
lock.acquire()
TOTAL += 1
lock.release()
print('Producer: I produced one.')
num += 1
if num >= 3:
# Now Shifu does it 3 A loaf of bread will get you off work .
print('Done.')
break
def consumer(lock):
""" consumer , You have to say something to buy bread ."""
global TOTAL
global END_FLAG
while not END_FLAG:
if TOTAL > 0:
print("Consumer: I am so happy.")
lock.acquire()
TOTAL -= 1
lock.release()
else:
time.sleep(2)
print("Consumer: I am waiting!")
print("Consumer: Oh no!")
def run():
lock = threading.Lock()
producers = []
for _ in range(PRODUCER_NUM):
p = threading.Thread(target=producer, args=(lock,))
producers.append(p)
p.start()
c = threading.Thread(target=consumer, args=(lock,))
c.start()
for p in producers:
p.join()
global END_FLAG
global TOTAL
while TOTAL:
# We have to wait until the bread is sold out .
time.sleep(1)
END_FLAG = True # close the door , Customer consumption should also be stopped
c.join()
if __name__ == "__main__":
run()

Now there are three masters working , Master Wu wants to know that the master's bread is more popular , What to do ?


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