开发者学堂课程【Python 入门 2020年版:进程间通信】学习笔记,与课程紧密联系,让用户快速学习知识。
课程地址:https://developer.aliyun.com/learning/course/639/detail/10473
进程间通信
内容介绍:
一、进程间通信
一、进程间通信
进程间通信举例讲解
进程间通信跟线程间通信很像
1.举例代码:
import os, multiprocessing, queue
def producer():
for i in range(10):
print('生产了+++++pid{}{}'. format(os.getpid(), i))
q.put(‘pid{}[}’. format(os.getpid(),i))
def consumer():
for i in range(10):
print( '消费了------'.format(q.get()))
if_ name_ =='_ main_' :
q=queue.Queue()
p1 = multiprocessing. Process (target=producer)
p1.start()
c2 = multiprocessing. Process (target=consumer)
c2.start()
运行发现 q 没有定义,因为两个进程之间要共同访问全局变量,但是多进程不共享全局变量。
加了 time.sleep 也不行,来一个局部变量 x,再用 args 把全局变量传过去。
2.代码:
import os, multiprocessing, queue
def producer(x):
for i in range(10):
print('生产了+++++pid{}{}'. format(os.getpid(), i))
q.put(‘pid{}[}’. format(os.getpid(),i))
def consumer(x):
for i in range(10):
print( '消费了------{}'.format(x.get()))
if_ name_ =='_ main_' :
q=queue.Queue()
p1 = multiprocessing. Process (target=producer,args=(q,))
p1.start()
c2 = multiprocessing. Process (target=consumer,args=(q,))
c2.start()
运行时报错, queue 导错了
3.代码:
import os, multiprocessing,time
def producer(x):
for i in range(10):
time.sleep(0.5)
print('生产了+++++pid{}{}'. format(os.getpid(), i))
q.put(‘pid{}[}’. format(os.getpid(),i))
def consumer(x):
for i in range(10):
time.sleep(0.4)
print( '消费了------{}'.format(x.get()))
if_ name_ =='_ main_' :
q=multiprocessing.Queue()
p1 = multiprocessing. Process (target=producer,args=(q,))
p1.start()
c2 = multiprocessing. Process (target=consumer,args=(q,))
c2.start()
运行结果:
生产了++++++pid1516 0
消费了-------pid1516 0
生产了++++++pid1516 1
消费了-------pid1516 1
......
4.多个进程生产代码:
import os, multiprocessing,time
def producer(x):
for i in range(10):
time.sleep(0.5)
print('生产了+++++pid{}{}'. format(os.getpid(), i))
q.put(‘pid{}[}’. format(os.getpid(),i))
def consumer(x):
for i in range(10):
time.sleep(0.4)
print( '消费了------{}'.format(x.get()))
if_ name_ =='_ main_' :
q=multiprocessing.Queue()
p1 = multiprocessing. Process (target=producer,args=(q,))
P2 = multiprocessing. Process (target=producer,args=(q,))
P3 = multiprocessing. Process (target=producer,args=(q,))
p1.start()
P2.start()
P3.start()
c2 = multiprocessing. Process (target=consumer,args=(q,))
c2.start()
运行结果:
生产了++++++pid9172 0
生产了++++++pid7776 0
生产了++++++pid1188 0
消费了-------pid9172 0
消费了-------pid7776 0
生产了++++++pid9172 1
生产了++++++pid7776 1
生产了++++++pid1188 1
消费了-------pid1188 0
消费了-------pid9172 1
生产了++++++pid9172 2
生产了++++++pid7776 2
生产了++++++pid1188 2
消费了-------pid1188 1
生产了++++++pid9172 3
......
注意:q 的类型是 multiprocessing 里的,进程里 q 要存参,线程不用。