由於 GIL (Global Interpreter Lock,全局解釋器鎖) 的關係,python中的多線程其實並非真正的多線程,想要充分地使用多核CPU的資源,在python中大部分狀況須要使用多進程。
使用多進程時,應注意如下幾點:html
方式一python
from multiprocessing import Process import time def f(name): time.sleep(1) print('hello', name,time.ctime()) if __name__ == '__main__': p_list = [] for i in range(3): p = Process(target=f, args=('alvin',)) p_list.append(p) p.start() for i in p_list: p.join() print('end') 運行結果: hello alvin Sun Aug 12 09:34:42 2018 hello alvin Sun Aug 12 09:34:42 2018 hello alvin Sun Aug 12 09:34:42 2018 end
方式二:多線程
from multiprocessing import Process import time class MyProcess(Process): def __init__(self): super(MyProcess, self).__init__() def run(self): time.sleep(1) print('hello', self.name,time.ctime()) if __name__ == '__main__': p_list=[] for i in range(3): p = MyProcess() p.start() p_list.append(p) for p in p_list: p.join() print('end') 運行結果: hello MyProcess-1 Sun Aug 12 09:45:07 2018 hello MyProcess-2 Sun Aug 12 09:45:07 2018 hello MyProcess-3 Sun Aug 12 09:45:07 2018 end
from multiprocessing import Process import os, time def info(title): print(title) print('module name: ', __name__) print('parent process: ', os.getppid()) print('process id: ', os.getpid()) def f(name): info('\033[31;1mfunction f\033[0m') print('hello', name) if __name__ == '__main__': info('\033[32;1mmain process line \033[0m') time.sleep(100) p = Process(target=info, args=('bob',)) p.start() p.join() 運行結果: main process line module name: __main__ parent process: 12248 process id: 1956
參考: http://www.cnblogs.com/yuanchenqi/articles/5745958.htmlapp