#encoding=utf-8
#python进程通信,使用multiprocessing的Queue来
#共享通信数据
#Process.run 如果在创建的时候不指定target,也可以将
#执行目标赋值给run,执行start会执行run函数
try:
from multiprocessing import Process, Pool, Queue
import time
import os
except ImportError,e:
print("Import Error: %s" % (e.message,))
g_ProductCount=5
class Producer(object):
def __init__(self):
pass
def product(self,q):
global g_ProductCount
print("proudce PID=0x%X" % (os.getpid(),))
for i in range(g_ProductCount):
print("put to Queue, i=%d" % (i,))
#加入队列中
q.put(i)
time.sleep(0.3)
return 100
class Consumer(object):
def __init__(self):
pass
def consume(self,q):
print("consume PID=0x%X" % (os.getpid(),))
global g_ProductCount
for i in range(g_ProductCount):
#从队列中读取数据
d=q.get()
print("get from Queue,i=%d" % (d,))
time.sleep(0.1)
#计算i的平方
print("result:%d" % (i**2,))
return 200
if __name__=="__main__":
print("Main process ID=0x%X" % (os.getpid(),))
p=Producer()
c=Consumer()
q=Queue(100)
pp=Process(target=p.product, args=(q,))
pc=Process(target=c.consume, args=(q,))
print("start producer process")
pp.start()
print("start consumer process")
pc.start()
pp.join()
pc.join()
print("pp.exitcode=%d" % (pp.exitcode))
print("pc.exitcode=%d" % (pc.exitcode))
q.close()
print("Main process End.")
python的multiprocessing.Process
最新推荐文章于 2022-12-31 16:49:16 发布