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

[Master Wus Python bakery] day 5

編輯: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, Master Wu invited two more masters , Now there are three masters working . Master Wu needs to know that the master's bread is more popular , Therefore, each master is required to make bread with the master's logo .

""" The bread made by each master has the master's logo on it , In this way, Master Wu can tell which master's bread is more popular ."""
import time
import threading
import random
TOTAL = []
END_FLAG = False
PRODUCER_NUM = 3
def producer(lock, p_num):
""" Making bread ."""
producer_flag = 'P:%s' % p_num
num = 0
global TOTAL
while True:
time.sleep(1)
lock.acquire()
TOTAL.append(producer_flag)
lock.release()
print('Producer: I produced one.')
num += 1
if num >= 3:
# Shifu do 3 A loaf of bread is coming 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:
lock.acquire()
producer_flag = TOTAL.pop()
print('Consumer: The flag is %s' % producer_flag)
choice_flag = random.choice(['P:0', 'P:1', 'P:2'])
if producer_flag != choice_flag:
print('Consumer: I don\'t want:', producer_flag)
TOTAL.append(producer_flag)
lock.release()
else:
time.sleep(2)
print("Consumer: I am waiting!")
print("Consumer: Oh no!")
def run():
lock = threading.Lock()
producers = []
for i in range(PRODUCER_NUM):
p = threading.Thread(target=producer, args=(lock, i,))
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()

Master Wu found that every customer has his own love , I will buy my favorite master's bread . How to sell the bread directly to the customers ?


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