二、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()

相关推荐