def task(name):
print('%s is running' % name)
time.sleep(3)
if __name__ == '__main__':
obj = Process(target=task, args=('egon',))
obj.daemon=True
obj.start() # 发送信号给操作系统
print('主')
2 互斥锁
互斥锁:
强调:必须是lock.acquire()一次,然后 lock.release()释放一次,才能继续lock.acquire(),不能连续的lock.acquire()
def task1(lock):
lock.acquire() #
print('task1:名字是egon')
time.sleep(random.randint(1,3))
print('task1:性别是male')
time.sleep(random.randint(1,3))
print('task1:年龄是18')
lock.release()
def task2(lock):
lock.acquire()
print('task2:名字是alex')
time.sleep(random.randint(1,3))
print('task2:性别是male')
time.sleep(random.randint(1,3))
print('task2:年龄是78')
lock.release()
def task3(lock):
lock.acquire()
print('task3:名字是lxx')
time.sleep(random.randint(1,3))
print('task3:性别是female')
time.sleep(random.randint(1,3))
print('task3:年龄是30')
lock.release()
if __name__ == '__main__':
p1=Process(target=task1,args=(mutex,))
p2=Process(target=task2,args=(mutex,))
p3=Process(target=task3,args=(mutex,))
# p1.start()
# p1.join()
# p2.start()
# p2.join()
# p3.start()
# p3.join()
p1.start()
p2.start()
p3.start()
iPC通信机制 Queue
# 队列:
#1、共享的空间
#2、是内存空间
#3、自动帮我们处理好锁定问题
from multiprocessing import Process,Manager,Lock
import time
mutex=Lock()
def task(dic,lock):
lock.acquire()
temp=dic['num']
time.sleep(0.1)
dic['num']=temp-1
lock.release()
if __name__ == '__main__':
m=Manager()
dic=m.dict({'num':10})
l=[]
for i in range(10):
p=Process(target=task,args=(dic,mutex))
l.append(p)
p.start()
for p in l:
p.join()
print(dic)
import time
import random
from multiprocessing import Process,Queue
def consumer(name,q):
while True:
res=q.get()
time.sleep(random.randint(1,3))
print('\033[46m消费者===》%s 吃了 %s\033[0m' %(name,res))
def producer(name,q,food):
for i in range(5):
time.sleep(random.randint(1,2))
res='%s%s' %(food,i)
q.put(res)
print('\033[45m生产者者===》%s 生产了 %s\033[0m' %(name,res))
if __name__ == '__main__':
#1、共享的盆
q=Queue()
#2、生产者们
p1=Process(target=producer,args=('egon',q,'包子'))
p2=Process(target=producer,args=('刘清政',q,'泔水'))
p3=Process(target=producer,args=('杨军',q,'米饭'))
#3、消费者们
c1=Process(target=consumer,args=('alex',q))
c2=Process(target=consumer,args=('梁书东',q))
p1.start()
p2.start()
p3.start()
c1.start()
c2.start()