python中进程间通信

进程间通信

进程之间不能像线程那样共享全局变量,所以进程间通信需要使用队列。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

import time
import multiprocessing

def (q):
while 1:
print(q.get())
time.sleep(1)

def work2(q):
while 1:
q.put("11111")
time.sleep(2)

def main():
q = multiprocessing.Queue(3)
w2 = multiprocessing.Process(target = work2,args = (q,))
w1 = multiprocessing.Process(target = work1,args = (q,))
w1.start()
w2.start()
w1.join()
w2.join()

if __name__ == "__main__":
main()