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 ?
demand : You want to initializ