作业28
手动书写生产者消费者代码
from multiprocessing import Process, JoinableQueue
import time
import random
def producer(name, food, q):
for i in range(1, 11):
time.sleep(random.randint(1, 2))
q.put(f"{food} {i}号")
print(f"{name}制造了{food} {i}号")
def consummer(name, q):
while 1:
food = q.get()
time.sleep(random.randint(1, 2))
print(f"{name}吃了{food}")
q.task_done()
if __name__ == '__main__':
q = JoinableQueue()
p1 = Process(target=producer, args=("egon", "包子", q))
p2 = Process(target=producer, args=("tank", "泔水", q))
c1 = Process(target=consummer, args=("jason", q))
c2 = Process(target=consummer, args=("yang", q))
c1.daemon = True
c2.daemon = True
p1.start()
p2.start()
c1.start()
c2.start()
p1.join()
p2.join()
q.join()
from multiprocessing import Process, Queue
import time
import random
def producer(name, food, q):
for i in range(1, 11):
time.sleep(random.randint(1, 2))
q.put(f"{food} {i}号")
print(f"{name}制造了{food} {i}号")
def consummer(name, q):
while 1:
food = q.get()
if food is None:
break
time.sleep(random.randint(1, 2))
print(f"{name}吃了{food}")
if __name__ == '__main__':
q = Queue()
p1 = Process(target=producer, args=("egon", "包子", q))
p2 = Process(target=producer, args=("tank", "泔水", q))
c1 = Process(target=consummer, args=("jason", q))
c2 = Process(target=consummer, args=("yang", q))
p1.start()
p2.start()
c1.start()
c2.start()
p1.join()
p2.join()
q.put(None)
q.put(None)
思考:如何实现TCP服务端并发的效果
1 socketserver.ThreadingTCPServer
2 多进程
3 多线程