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

[Master Wus Python bakery] day 8

編輯: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 .

In order to check the problem that the customer placed an order but didn't get the bread , Master Wu asked each Baker to produce bread according to the order number , And the bread is given to the corresponding customer according to the order number .

""" Each Baker produces bread according to the number of orders , And the bread should be given to the customer according to the order number ."""
import time
import threading
import multiprocessing
import random
import zmq
PRODUCER_NUM = 3
def order(topic, order_id, pub_socket):
""" Place an order ."""
print('Order:%s, topic:%s' % (order_id, topic))
pub_socket.send_multipart([topic.encode(), order_id.encode()])
def worker(topic, context):
sub_socket = context.socket(zmq.SUB)
sub_socket.connect("tcp://localhost:5555")
sub_socket.setsockopt(zmq.SUBSCRIBE, topic.encode('utf8'))
sub_socket.setsockopt(zmq.RCVTIMEO, 2000) # Set accept timeout
print('Windows:', topic)
while 1:
msg = None
try:
msg, order_id = sub_socket.recv_multipart()
except Exception as e:
pass
else:
if msg:
# Master received the order , The bread is made and returned
print('Finished: %s, %s' % (order_id.decode(), msg.decode()))
time.sleep(1)
def run_bakery():
context = zmq.Context()
workers = []
for i in range(PRODUCER_NUM):
# Each chef corresponds to a bakery team
topic = 'P:%s' % i
w = threading.Thread(target=worker, args=(topic, context))
workers.append(w)
w.start()
for w in workers:
w.join()
def run_customer():
# Simulated customer order
context = zmq.Context()
pub_socket = context.socket(zmq.PUB)
pub_socket.bind("tcp://*:5555")
time.sleep(2)
orders_num = random.randint(6, 10)
for j in range(orders_num):
i = random.randint(0, PRODUCER_NUM-1)
topic = 'P:%s' % i
order_id = "id_%s" % j
time.sleep(0.1)
order(topic, order_id, pub_socket)
def run():
p1 = multiprocessing.Process(target=run_bakery)
p2 = multiprocessing.Process(target=run_customer)
p1.start()
p2.start()
p1.join()
p2.join()
if __name__ == "__main__":
run()

The National Day is over , Will master Wu's bakery continue to open ?


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