写在前面,进程同步控制有锁,信号量,事件
进程间通信有 队列和管道
- 信号量
相当于多个锁
import os
import time
import random
from multiprocessing import Process, Semaphore
def ro(i, sem):
sem.acquire()
print('%s in room'.format(i))
time.sleep(random.randint(5,6))
print('%s out room'.format(i))
sem.release()
if __name__ == "__main__":
sem = Semaphore(4)
for i in range(20):
p = Process(target=ro, args=(i, sem))
p.start()
- 事件
控制进程的动作
from threading import Event
e = Event() # 创建了一个事件
print(e.is_set()) # 查看一个事件的状态
e.set() # 将事件的状态设置为 True
print(e.is_set())
e.wait() # 根据 e.is_set() 值决定是否阻塞
e.clear() # 将事件状态设置为 False
print(e.is_set())
红绿灯问题
import time
import random
from multiprocessing import Process, Event
def cars(e, i):
if not e.is_set():
print('car%s在等待'%i)
e.wait()
print('%s car通过'%i)
def light(e):
while True:
if e.is_set():
e.clear()
print('红灯亮了')
else:
e.set()
print('绿灯亮了')
time.sleep(2)
if __name__ == '__main__':
e = Event()
traffic = Process(target=light, args=(e,))
traffic.start()
for i in range(20):
car = Process(target=cars, args=(e, i))
car.start()
time.sleep(random.random())
生产者与消费者问题
import time
import random
from multiprocessing import Process, Queue
def consumer(q, name):
while True:
food = q.get()
if food is None:
print('获取到了一个空')
break
print('%s 消费了 %s'%(name, food))
time.sleep(random.randint(1,3))
def producer(name, food, q):
for i in range(4):
time.sleep(random.randint(1,3))
f = "%s 生产了 %s%s" % (name, food, i)
print(f)
q.put(f)
if __name__ == '__main__':
q = Queue(20)
p1 = Process(target=producer, args=('a', 'w', q))
p2 = Process(target=producer, args=('b', 'w', q))
c1 = Process(target=consumer, args=(q, 'c1'))
c2 = Process(target=consumer, args=(q, 'c2'))
p1.start()
p2.start()
c1.start()
c2.start()
p1.join()
p2.join()
q.put(None)
q.put(None)
这样太麻烦了,因为有几个生产这就需要放置几个 None。可以使用 JoinableQueue
import time
import random
from multiprocessing import Process
from multiprocessing import JoinableQueue
def consumer(q, name):
while True:
food = q.get()
print('%s 消费了 %s'%(name, food))
time.sleep(random.randint(1,3))
q.task_done()
def producer(name, food, q):
for i in range(4):
time.sleep(random.randint(1,3))
f = "%s 生产了 %s%s" % (name, food, i)
print(f)
q.put(f)
q.join() # 阻塞 直到一个队列中的数据全部被处理完毕
if __name__ == '__main__':
q = JoinableQueue(20)
p1 = Process(target=producer, args=('a', 'w', q))
p2 = Process(target=producer, args=('b', 'w', q))
c1 = Process(target=consumer, args=(q, 'c1'))
c2 = Process(target=consumer, args=(q, 'c2'))
p1.start()
p2.start()
c1.daemon = True
c2.daemon = True
c1.start()
c2.start()
p1.join()
p2.join()
网友评论