參考
[1.] threading — Thread-based parallelism
[2.] Python-GIL GlobalInterpreterLock
[2.1] Python中GIL對多線程性能的影響
[3.] 維基百科- GIL全局解釋器鎖
[4.] Python多進程multiprocessing使用示例
一、線程並行概述
關鍵詞 | 釋義 |
---|---|
GIL | 全局解釋器鎖,用來保證Python解釋器某時刻只有一個線程運行;儘管解釋器中可以運行多個線程,但是在任意給定時刻只有一個線程會被解釋器執行。 |
1. GIL (Global Interpreter Lock)
GIL是語言解釋器中的一種機制,用於同步線程,使得任何時候僅有一個線程在執行。 常用的GIL解釋器有CPython與Ruby MRI。Python使用的解釋器是CPython。
CPython的線程是操作系統的原生線程。在Linux上爲pthread,在Windows上爲Win thread,完全由操作系統調度線程的執行。一個Python解釋器進程內有一個主線程,以及多個用戶程序的執行線程。即便使用多核心CPU平臺,由於GIL的存在,也將禁止多線程的並行執行。
在Python中,線程啓動後,只有執行完纔會停止。
Python 3.2開始使用新的GIL。新的GIL實現中用一個固定的超時時間來指示當前的線程放棄全局鎖。在當前線程保持這個鎖,且其他線程請求這個鎖時,當前線程就會在5毫秒後被強制釋放該鎖。
2. 解決GIC對線程的並行限制問題 — 創建獨立的進程
- Python 2.6引入多進程包 multiprocessing;
- 將關鍵組件用C/C++編寫爲Python擴展,通過ctypes使Python程序直接調用C語言編譯的動態鏈接庫的導出函數。
二、關於Thread類
構造方法:
/*
group: 線程組,目前還沒有實現,庫引用中提示必須是None;
target: 要執行的方法;
name: 線程名;
args/kwargs: 要傳入方法的參數
*/
Thread(group=None, target=None, name=None, args=(), kwargs={})
1. 使用Thread
_0. Thread 和 threading的比較
Python已經使用threading來替代Thread了,傳統的Thread功能不太完善,缺少資源的額釋放和競態條件的控制。
_1.使用方式
- a.以類的方式,繼承、創建線程
- b.將要執行的方法作爲參數傳給Thread的構造方法
_2.使用示例
ex01_thread.py
#!/usr/bin/env python
from threading import Thread
class MyThread(Thread):
def __init__(self, name, args):
# assign name for parent class's __init__(...)
super(MyThread, self).__init__(name=name)
self.data = args
# rewrite the run() method
def run(self):
print(self.name, self.data)
if __name__ == '__main__':
thread = MyThread("Henry's Tel is ", '007')
thread.start()
ex02_thread.py
#!/usr/bin/env python
from threading import *
class MyThread():
def __init__(self):
pass
def run(self, name, data):
print str(name)+str(data)
def start(self):
try:
thread_list = []
thread = Thread(
target=self.run,
args=(
"Henry",
" is threading()!\n"))
thread_list.append(thread)
for thread in thread_list:
thread.start()
print thread.isAlive()
thread.join()
print thread.isAlive()
except():
print "Err: "+self.__func__
return False
if __name__ == '__main__':
module = MyThread()
module.start()
執行: python ex02_thread.py,結果:
Henry is threading()!
True
False
三、關於multiprocessing
unifished at here
1. 使用multiprocessing
注意:
進程實例不能放在類中定義
#!/usr/bin/env python
import multiprocessing
def main_process():
name = multiprocessing.current_process().name
print(name, "start...")
print(name, "end")
def sub_process():
name = multiprocessing.current_process().name
print(name, "start...")
print(name, "end")
if __name__ == '__main__':
process_list = []
process_list.append(multiprocessing.Process(name="process(service)", target=main_process))
process_list.append(multiprocessing.Process(name="process(client)", target=sub_process))
for process in process_list:
process.start()
for process in process_list:
process.join()