• 作业28


    作业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 多线程

  • 相关阅读:
    vs13的内存占用 关闭之
    Java基础 -5
    Java基础 -4.6
    Java基础 -4.5
    Java基础 -4.4
    Java基础 -4.3
    Java基础 -4.2
    Java基础 -4
    Java基础 -3.5
    Java基础 -3.4
  • 原文地址:https://www.cnblogs.com/achai222/p/12764340.html
Copyright © 2020-2023  润新知