标签:优先 offer targe ssi read href lock pen python程序
参考博客:https://www.cnblogs.com/vamei/archive/2012/10/12/2721484.html
Python的线程或进程都是调用操作系统的原生线程或进程,但是由于GIL的存在,python多线程并不能利用cpu多核的优势。而python的进程是不存在GIL的,各个进程间的数据是独立的安全的,所有python多进程可以利用多核优势。
各自适用情况:
python多线程: I/O 操作密集型任务
python多进程: CPU密集型任务
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. multiprocessing包是Python中的多进程管理包,用类似于线程模块的API来创建进程(multiprocessing的很大一部份与threading使用同一套API,只不过换到了多进程的情境)。 多进程管理包提供本地和远程的并发,通过使用子进程而不是线程有效的避开了GIL 由于这个原因,multiprocessing允许程序员充分利用给定机器上的多个处理器。 它可以在Unix和Windows上运行。
与threading.Thread类似,它可以利用multiprocessing.Process对象来创建一个进程。该进程可以运行在Python程序内部编写的函数。该Process对象与Thread对象的用法相同,也有start(), run(), join()的方法。此外multiprocessing包中也有Lock/Event/Semaphore/Condition类
但在使用这些共享API的时候,我们要注意以下几点:
Process.PID中保存有PID,如果进程还没有start(),则PID为None。
import multiprocessing import time import os def run(name): time.sleep(2) print(‘hello‘, name) if __name__ == ‘__main__‘: start_time = time.time() p_list = [] for i in range(10): p = multiprocessing.Process(target=run, args=(‘bob%s‘ % i,)) # 创建一个进程对象 p.start() print(p.name, p.pid) # 进程名 和 pid p_list.append(p) # p.join() # 和线程一样,join会阻塞 for p in p_list: p.join() print(‘parent process‘, os.getppid()) print(‘total time‘, time.time()-start_time)
# -*- coding: UTF-8 -*- import multiprocessing import time import os import threading def threading_run(name): print(‘name:‘, name) def run(name): time.sleep(2) t = threading.Thread(target=threading_run, args=(name,)) # 定义线程 t.start() # print(‘hello‘, name) if __name__ == ‘__main__‘: start_time = time.time() for i in range(10): p = multiprocessing.Process(target=run, args=(‘bob%s‘ % i,)) # 进程 p.start() # print(p.name, p.pid) print(‘parent process‘, os.getppid())
注:和线程一样,主进程也默认不会等待子进程结束
from multiprocessing import Process import os def info(title): print(title) print(‘module name:‘, __name__) print(‘parent process:‘, os.getppid()) print(‘process id:‘, os.getpid()) print("\n\n") def f(name): info(‘\033[31;1mfunction f\033[0m‘) print(‘hello‘, name) if __name__ == ‘__main__‘: info(‘\033[32;1mmain process line\033[0m‘) p = Process(target=f, args=(‘bob‘,)) p.start() p.join()
结果:
main process line module name: __main__ parent process: 2464 process id: 13628 function f module name: __mp_main__ parent process: 13628 process id: 17480 hello bob
注:
parent process: 2464 是我电脑中PyCharm 的进程号
process id: 13628 是 主进程(‘__main__‘)的进程号
process id: 17480 是 子进程 p 的进程号
所以可以看出,所有的进程都是由父进程启动的
标签:优先 offer targe ssi read href lock pen python程序
原文地址:http://www.cnblogs.com/bigberg/p/7993276.html