二、Python开发---25、多线程多进程(2)
多进程的几种方法
Lock:可以避免访问资源时的冲突
Pool:可以提供指定数量的进程
Queue:多进程安全的队列,实现多进程之间的数据传递
Pipe:实现管道模式下的消息发送与接收
Lock(加锁)
#加锁 ‘‘‘ 输出为 work_1 start work_2 start work_1 end work_2 end ‘‘‘ import time import multiprocessing def work_1(f,n,lock): print(‘work_1 start‘) lock.acquire() for i in range(n): with open(f,‘a‘) as fs: fs.write(‘i love pyhton \n‘) time.sleep(1) print(‘work_1 end‘) lock.release() def work_2(f,n,lock): print(‘work_2 start‘) lock.acquire() for i in range(n): with open(f,‘a‘) as fs: fs.write(‘come on baby \n‘) time.sleep(1) print(‘work_2 end‘) lock.release() if __name__ == ‘__main__‘: lock=multiprocessing.Lock() p1 = multiprocessing.Process(target=work_1,args = (‘file.txt‘,3,lock)) p2 = multiprocessing.Process(target=work_2, args=(‘file.txt‘, 1,lock)) p1.start() p2.start()
相关推荐
CloudXli 2020-04-07
oXiaoChong 2020-04-07
学习备忘录 2020-02-18
assastor 2020-01-23
farewellpoem 2020-11-09
chunjiekid 2020-08-16
lhtzbj 2020-08-13
learnpy 2020-07-19
kyelu 2020-07-09
小菜鸟的代码世界 2020-06-17
举 2020-06-14
bizercsdn 2020-06-06
usepython 2020-05-31
haokele 2020-05-31
fengling 2020-05-31
maimang00 2020-05-30
yawei 2020-05-30
坚持是一种品质 2020-05-28
laityc 2020-05-27