Loading

进程间通信

案例描述:

一个进程执行加一操作,另一个进程每隔5秒打印一次。

一、用进程实现(需要进程间进行通信)

1、消息队列

Queue

def add(queue):
    # global aa
    aa =0
    while aa<5:
        # print(aa)
        time.sleep(1)
        aa += 1
        queue.put(aa)

def prin(queue):
    # global aa

    while True:

        time.sleep(5)
        aa = queue.get()
        print(aa)

if __name__ == '__main__':
    q = multiprocessing.Queue()


    p1 = multiprocessing.Process(target=add, args=(q,))

    p2 = multiprocessing.Process(target=prin, args=(q,))

    p1.start()
    p2.start()

    p1.join()
    p2.join()
    print("主进程结束")

2、pipe

Pipe方法返回(conn1,conn2)代表一个管道的两个端

def add(pipe):
    # global aa
    aa =0
    while aa<100:
        # print(aa)
        time.sleep(1)
        aa += 1
        if aa % 5 == 0:
            pipe.send(aa)


def prin(pipe):
    # global aa

    while True:

        aa = pipe.recv()
        # aa = queue.get()
        print(aa)

if __name__ == '__main__':
    con1, con2 = multiprocessing.Pipe()


    p1 = multiprocessing.Process(target=add, args=(con1,))

    p2 = multiprocessing.Process(target=prin, args=(con2,))

    p1.start()
    p2.start()

    p1.join()
    p2.join()
    print("主进程结束")

二、用线程实现(需要定义全局变量)

def add():
    global aa
    while aa<100:
        time.sleep(1)
        aa += 1

def prin():
    global aa
    while aa <100:
        time.sleep(5)
        print(aa)


if __name__ == '__main__':
    aa = 0
    thread1 = threading.Thread(target=add)
    thread2 = threading.Thread(target=prin)

    thread1.start()
    thread2.start()
    thread1.join()
    thread2.join()
    print("主进程结束")

 

posted @ 2021-09-03 17:18  climber_dzw  阅读(28)  评论(0编辑  收藏  举报