ipconfiger
2016-03-15 22:33:59 +08:00
给个栗子给你
from multiprocessing import Process, Queue
import os, time, random
# 写数据进程执行的代码:
def write(q):
for value in ['A', 'B', 'C']:
print 'Put %s to queue...' % value
q.put(value)
time.sleep(random.random())
# 读数据进程执行的代码:
def read(q):
while True:
if not q.empty():
value = q.get(True)
print 'Get %s from queue.' % value
time.sleep(random.random())
else:
break
if __name__=='__main__':
# 父进程创建 Queue ,并传给各个子进程:
q = Queue()
pw = Process(target=write, args=(q,))
pr = Process(target=read, args=(q,))
# 启动子进程 pw ,写入:
pw.start()
# 等待 pw 结束:
pw.join()
# 启动子进程 pr ,读取:
pr.start()
pr.join()
# pr 进程里是死循环,无法等待其结束,只能强行终止:
print
print '所有数据都写入并且读完'