多进程/多线程间通信与同步
进程通信方式一Queue:
# coding=utf-8
from multiprocessing import Queue, Process
import random
def getter(name, queue):
print 'Son process %s' % name
while True:
try:
value = queue.get(True, 10)
# block为True,就是如果队列中无数据了。
# |—————— 若timeout默认是None,那么会一直等待下去。
# |—————— 若timeout设置了时间,那么会等待timeout秒后才会抛出Queue.Empty异常
# block 为False,如果队列中无数据,就抛出Queue.Empty异常 等价于queue.get_nowait() 队列为空立即异常返回
print "Process getter get: %f" % value
except QueueEmpty:
break
def putter(name, queue):
print "Son process %s" % name
for i in range(0, 1000):
value = random.random()
queue.put(value)
# 放入数据 put(obj[, block[, timeout]])
# 若block为True,如队列是满的:
# |—————— 若timeout是默认None,那么就会一直等下去
# |—————— 若timeout设置了等待时间,那么会等待timeout秒后,如果还是满的,那么就抛出Queue.Full.
# 若block是False,如果队列满了,直接抛出Queue.Full
print "Process putter put: %f" % value
if __name__ == '__main__':
queue = Queue()
getter_process = Process(target=getter, args=("Getter", queue))
putter_process = Process(target=putter, args=("Putter", queue))
getter_process.start()
putter_process.start()
进程通方式二Pipe:
# coding=utf-8
from multiprocessing import Pipe, Process
def son_process(x, pipe):
_out_pipe, _in_pipe = pipe
# 关闭fork过来的输入端
_in_pipe.close()
while True:
try:
msg = _out_pipe.recv()
print msg
except EOFError:
# 当out_pipe接受不到输出的时候且输入被关闭的时候,会抛出EORFError,可以捕获并且退出子进程
break
if __name__ == '__main__':
out_pipe, in_pipe = Pipe(True)
son_p = Process(target=son_process, args=(100, (out_pipe, in_pipe)))
son_p.start()
# 等pipe被fork 后,关闭主进程的输出端
# 这样,创建的Pipe一端连接着主进程的输入,一端连接着子进程的输出口
out_pipe.close()
for x in range(1000):
in_pipe.send(x)
in_pipe.close()
son_p.join()
print "主进程也结束了"
线程通信方式:全局变量
线程在对一个全局变量进行改变的时候,会竞争资源,导致结果不准确,因此需要线程同步。
import threading
import time
class MyThread(threading.Thread):
def run(self):
global num
time.sleep(1)
if mutex.acquire(1): //mutex.acquire()加锁,超时时间为1
num = num+1
msg = self.name+' set num to '+str(num)
print msg
mutex.release() //解锁
num = 0
mutex = threading.Lock() //创建互斥锁
def test():
for i in range(5):
t = MyThread()
t.start()
if __name__ == '__main__':
test()