多线程和多进程通过队列进行数据交换代码模板

from multiprocessing import Pool, Manager
import threading
import time
import random
import os


def add(q):
    while True:
        num = random.randint(1,100)
        q.put(num)
        print("线程 A 往队列中写入了 %d" % num)
        print(" 当前队列中的任务数:%d" % q.qsize())
        time.sleep(0.1)
        if q.full():
            print("当前队列中的任务数已满,睡觉10s")
            time.sleep(10)


def run(q):
    while True:
        print(" 当前队列中的任务数:%d" % q.qsize())
        if q.qsize() > 0:
            qqqq_info = q.get()
            print("子进程ID:%d 处理了队列中的一个数据 %d" % (os.getpid(), qqqq_info))
            time.sleep(1)
        else:
            print("子进程ID:%d 发现队列中不存在任务,睡觉5s" % os.getpid())
            time.sleep(5)


if __name__ == "__main__":
    m = Manager()
    q = m.Queue(50)
    p = Pool(4)
    threading.Thread(target=add, args=(q,)).start() # 写入
    while True:
        try:
            for i in range(10):
                print(1111111)
                p.apply_async(run, args=(q,))
            print(2222222)
            p.close()
            p.join()
        except:
            pass
posted @ 2020-04-03 21:03  zpchcbd  阅读(178)  评论(0)    收藏  举报