day10-多进程的基本语法

一、概述

  之前我们了解的线程,接下来我们学习多进程,进程之间是相互独立的,python是启动进程的时候,是启动的是原生进程。进程是没有GIL锁的,而且不存在锁的概念,进程之间的数据是不能共享的,而线程是可以的。

  英文解释如下:

  multiprocessing is a package that supports spawning processes using an API similar to the threading module. The multiprocessing package offers both local and remote concurrency, effectively side-stepping the Global Interpreter Lock by using subprocesses instead of threads. Due to this, the multiprocessing module allows the programmer to fully leverage multiple processors on a given machine. It runs on both Unix and Windows.

二、线程的使用场景  

2.1、使用场景

  1. IO操作:不占用cpu的操作,比如:从磁盘上读块数据,从网络读块数据,从内存上读块数据都算是io的操作。
  2. 计算是占用cpu的,比如:计算1+1。线程利用上下文切换,也是消耗资源的。如果大量计算,用多线程就不快了,线程之前的来回切换,运算不要用。
  3. python的多线程不适合cpu的密集型操作的任务。但是,适合io密集型的任务,比如:socket_server 的使用。

三、进程

3.1进程的定义

说明:用muliprocessing这个包中的Process来定义多进程,跟定义多线程差不多。

 1 import multiprocessing,time
 2 
 3 def run(name):
 4     time.sleep(2)
 5     print("hello",name)
 6 
 7 if __name__ == "__main__":
 8     p_obj_list=[]
 9     for i in range(10):
10         p = multiprocessing.Process(target = run ,args = ("keven",))
11         p.start()
12         p_boj_list.append(p)
13 
14     for p in p_obj_list:
15         p.join()

3.2、进程中嵌套入线程

说明:在进程中去嵌套入线程

 1 from multiprocess import Process
 2 import time,threading
 3 
 4 def thread_run(name):
 5     print("{}:{}".format(name,threading.get_ident()))
 6 
 7 def run(name):
 8     time.sleep(2)
 9     t=threading.Thread(target = thead_run,args=(name,))
10     t.start()
11 
12 if __name__ == “__main__":
13     p_obj_list = []
14     for i in range(10)
15     p =Process(target =run,args=("keven %s" %i))
16     p.start()
17     p_obj_list.append(p)
18 
19     for p in p_obj_list:
20     p.join()

3.3、父进程

说明:每一个子进程都有由父进程启动的,即便是我们这种进程也是由一个父进程启动的。

by the way:linux 所有进程都有有 1 进程启动的

 1 from multiprocessing import Process
 2 
 3 import os
 4 
 5 def info(title):
 6     print(title)
 7     print("module name:",__name__)
 8     print(”parent process:“,os.getppid())
 9     print(” process id :“,os.getpid())
10     print("\n\n")
11 
12 def f(name):    
13     info("\033[32;1m function f \033[0m")
    print("hello",name)
  

  if __name__ = "__main__":
14 p = Process(target=f,args=("bob",)) 15 p.start() 16 p.join()

 

posted @ 2018-03-21 10:51  东郭仔  阅读(117)  评论(0)    收藏  举报