WEEK9:Python协程、异步IO

  • 使用场景:IO操作不占用CPU,计算占用CPU。Python的多线程不适合CPU密集操作型的任务,适合IO操作密集型的任务。
  • 多进程的基本语法
    • 启动进程和在进程中启动线程
       1 import multiprocessing
       2 import time,threading
       3 
       4 def thread_run(): #线程函数
       5     print(threading.get_ident())
       6 
       7 def run(name): #进程函数
       8     time.sleep(2)
       9     print("hello",name)
      10     t=threading.Thread(target=thread_run,) #在进程中启动线程
      11     t.start()
      12 
      13 if __name__ == "__main__":
      14     for i in range(10):
      15         p=multiprocessing.Process(target=run,args=('bob %s' %i,)) #启动进程
      16         p.start()
    • 获取父进程和子进程的ID
       1 from multiprocessing import Process
       2 import os
       3 
       4 def info(title):
       5     print(title)
       6     print('module name:', __name__) #获取模块名称即父进程名称
       7     print('parent process:', os.getppid()) #获取父进程ID
       8     print('process id:', os.getpid()) #获取本进程的ID
       9     print("\n\n")
      10 
      11 def f(name):
      12     info('called from child process function f')
      13     print('hello', name)
      14 
      15 if __name__ == '__main__':
      16     info('main process line') #父进程为主函数'__main__',
      17     p = Process(target=f, args=('bob',)) #父进程为info函数
      18     p.start()
    • 进程间通信
       1 from multiprocessing import Process, Queue #进程间通信使用的是multiprocessing中的Queue
       2 import threading
       3 
       4 def f(qq):
       5     print("in child:",qq.qsize())
       6     qq.put([42, None, 'hello'])
       7 
       8 if __name__ == '__main__':
       9     q = Queue()
      10     q.put("test123")
      11     p = Process(target=f, args=(q,))
      12     p.start()
      13     p.join()
      14     print("444",q.get_nowait())
      15     print("444",q.get_nowait())

猜你喜欢

转载自www.cnblogs.com/JYLCSS/p/11070406.html
今日推荐