Python multithreading與multiprocessing使用
一支Python程式在運行的時候如果沒加入multithreading或multiprocessing的設計,程式只會一行一行執行無法發揮CPU性能,multithreading或multiprocessing都是讓程式在電腦上進行多工的方式,一個程式要運行時得先建立process,而一個process內又運行著thread用來運行程式,因此若不使用multithreading或multiprocessing方式進行程式開發,程式就只能在一個process裡的thread執行了。
Python的解釋器在每一個process內都設了一個GIL(Global Interpreter Lock),用來避免資源死鎖,這是Python語言獨有的設計,GIL確保Python應用程式一次這會有一個Thread在運行,這也就是Python在這方面令許多人垢病的地方,關於GIL的歷史淵源,在此不加以探究,學習如何減少GIL對程式帶來的影響才是重點。
至於要使用multithreading還是multiprocessing,這得取決於程式考量,multithreading是存在於process,因此較為輕量,但會受到GIL的限制,用於IO-bound較為適合,而multiprocessing適合用於CPU-bound,主要在於IO-bound的情境CPU大部分時間都在等待IO操作完成,因此任務越多CPU使用率也越高,而CPU-bound因CPU較為忙碌,若使用multithreading的方式,需花在任務切換的時間就越多,如此一來CPU執行效率就越低。
說了這麼多JR將multithreading與multiprocessing記錄下來,使用時機對了,可讓程式效能增進不少。
程式實作
Python程式:multithreading_demo.py
import math
import os
from threading import Thread
def thread_demo(index):
print('thread:', index)
for i in range(0, 60000000):
math.sqrt(i)
def main():
threads = []
for i in range(os.cpu_count()):
threads.append(Thread(target=thread_demo, args=(i,)))
for thread in threads:
thread.start()
for thread in threads:
thread. Join()
if __name__ == "__main__":
main()
Python程式:multiprocessing_demo.py
import math
import os
from multiprocessing import Process
def thread_demo(index):
print('process:', index)
for i in range(0, 60000000):
math.sqrt(i)
def main():
threads = []
for i in range(os.cpu_count()):
threads.append(Process(target=thread_demo, args=(i,)))
for thread in threads:
thread.start()
for thread in threads:
thread.join()
if __name__ == "__main__":
main()