61 - 进程之间的通信

用python创建两个进程,在这两个进程之间如何通信呢?

from multiprocessing import Queue, Process
import time
import random

list1 = ["java", "Python", "js"]


def write(queue):
    for value in list1:
        print(f'正在向队列中添加数据-->{value}')
        queue.put_nowait(value)
        time.sleep(random.random())


def read(queue):
    while True:
        if not queue.empty():
            value = queue.get_nowait()
            print(f'从队列中取到的数据为-->{value}')
            time.sleep(random.random())
        else:
            break


if __name__ == '__main__':
    queue = Queue()
    write_data = Process(target=write, args=(queue,))
    read_data = Process(target=read, args=(queue,))

    write_data.start()
    write_data.join()
    read_data.start()
    read_data.join()
    print('ok')
正在向队列中添加数据-->java
正在向队列中添加数据-->Python
正在向队列中添加数据-->js
从队列中取到的数据为-->java
从队列中取到的数据为-->Python
从队列中取到的数据为-->js
ok

62 - 如何为一个线程函数传递参数

发布了208 篇原创文章 · 获赞 249 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_29339467/article/details/104804788
61