python进程间通讯 能传值吗?

进程A,是主进程。有自己的任务

进程B,是一个计时器(比如time.sleep)

当B的计时到了后,送一个值给A。A就会执行一个特定的函数。。

进程间能这样传值吗?

用什么实现。谢谢

阅读 4.9k
2 个回答

能啊,管道挺适合的,利用 sendrecv 很容易实现两个进程之间的通讯:

# coding: utf-8
import multiprocessing
import time
def proc1(pipe):
    while True:
        for i in range(100):
            print("send: %s" % i)
            pipe.send(i)
            time.sleep(2)

def proc2(pipe):
    while True:
        print("proc2 rev: %s" % pipe.recv())
        time.sleep(2)

if __name__ == "__main__":
    pipe = multiprocessing.Pipe()
    p1 = multiprocessing.Process(target=proc1, args=(pipe[0],))
    p2 = multiprocessing.Process(target=proc2, args=(pipe[1],))
    p1.start()
    p2.start()
    print("hello world")

进程间通讯方式有很多种:
1,共享内存;
2,信号量;
3,管道;
4,消息队列;

根据具体业务需求来选择,查查相关文档了解下就会用了。

推荐问题