python 多进程多线程生产消费

from multiprocessing import Process, Queue
from threading import Thread
import random
from time import sleep


def TH1(q_th1):
    while 1:
        a = random.randint(0, 100)
        q_th1.put(a)
        print('\r进程1的线程1生产了:', a)
        sleep(random.randint(1, 5))


def TH2(q_th2):
    while 1:
        a = q_th2.get()
        print('\r进程1的线程2消费了:', a)
        sleep(random.randint(1, 5))


def P1(q_th1, q_th2):
    th1 = Thread(target=TH1, args=(q_th1, ))
    th2 = Thread(target=TH2, args=(q_th2, ))
    th1.start()
    th2.start()
    th1.join()
    th2.join()


def TH3(q_th1):
    while 1:
        a = q_th1.get()
        print('\r进程2的线程1消费了:', a)
        sleep(random.randint(1, 5))


def TH4(q_th2):
    while 1:
        a = random.randint(0, 100)
        q_th2.put(a)
        print('\r进程2的线程2生产了:', a)
        sleep(random.randint(1, 5))


def P2(q_th1, q_th2):
    th3 = Thread(target=TH3, args=(q_th1,))
    th4 = Thread(target=TH4, args=(q_th2,))
    th3.start()
    th4.start()
    th3.join()
    th4.join()


if __name__ == '__main__':
    q_th1 = Queue()
    q_th2 = Queue()
    p1 = Process(target=P1, args=(q_th1, q_th2))
    p2 = Process(target=P2, args=(q_th1, q_th2))
    p1.start()
    p2.start()

多进程多线程生产消费模式

你可能感兴趣的:(python,多进程,python)