python进程间通信示例—队列

1、功能描述:

Queue 为例,在⽗进程中创建两个⼦进程,⼀个往 Queue ⾥写数据,
⼀个从 Queue ⾥读数据。

2、示例代码:

from multiprocessing import Process
from multiprocessing import Queue
import os
import time
import random


def write(q):
    for value in ['A', 'B', 'C']:
        print('put %s to queue...' % value)
        q.put(value)
        time.sleep(random.random())


def read(q):
    while True:
        if not q.empty():
            value = q.get(True)
            print('get %s from queue.' % value)
        else:
            break


if __name__ == '__main__':
    q = Queue()
    pw = Process(target=write, args=(q,))
    pr = Process(target=read, args=(q,))
    pw.start()
    pw.join()
    pr.start()
    pr.join()
    print('all data has wrote and read! ')

你可能感兴趣的:(python,前端,开发语言)