- 
              进程是操作系统分配内存的最小单位
- 
              Python中进程用到的库 multiprocessing
- 
              简单的多进程示例
            
              from multiprocessing import Process
from time import time,sleep
from random import randint
def download_task(task_name):
    print(task_name+'开始下载')
    time =randint(1,5)
    sleep(time)
    print(task_name+f'下载结束,用时{time}s')
def main():
    print('开始下载。。。')
    start_time = time()
    p1 = Process(target=download_task,args=('task_1',))
    p1.start()
    p2 = Process(target=download_task,args=('task_2',))
    p2.start()
    p1.join()
    p2.join()
    end_time = time()
    print(f'下载结束,总用时{end_time-start_time}s')
if __name__ == '__main__':
    main()
            
          
          - 
              进程间的通信
- 多进程的内存空间是独立的不能使用普通的全局变量来传递信号
- 可以使用multiprocessing 中的 Queue、Pipe、Manager、Event
- 今天只复习queue和pipe
- 
              Queue 实现进程间通信示例如下:要注意的是:Queue 是为进程服务的而 queue中的Queue 是为线程服务的 
              from multiprocessing import Process,Queue,current_process def add_task(q): print(f'子进程{current_process().pid}操作') q.put('python') def main(): #创建进程通信的 Queue q = Queue() #创建子进程 p = Process(target=add_task,args=(q,)) p.start() print(f'父进程{current_process().pid}读取') print(q.get()) p.join() if __name__ == '__main__': main()
- 
              Pipe 实现进程间通信,示例如下: 
            
              from multiprocessing import Process,Pipe,current_process
def add_task(p_b):
    print(f"进程 {current_process().pid} 写入")
    p_b.send("python")
def main():
    #创建管道 ,返回管道两端
    p_a ,p_b= Pipe()
    p =Process(target=add_task,args=(p_b,))
    p.start()
    print(f"进程 {current_process().pid} 读取")
    print(p_a.recv())
    p.join()
if __name__ == '__main__':
    main()
            
          
          好了 进程今天就复习到这儿。明晚复习线程。。。
加油!


 
					 
					