python3多线程编程_Python 3多线程编程学习笔记-基础篇
本文是學習《Python核心編程》的學習筆記,介紹了Python中的全局解釋器鎖和常用的兩個線程模塊:thread, threading,并對比他們的優缺點和給出簡單的列子。
全局解釋器鎖(GIL)
Python代碼的執行都是有Python虛擬機進行控制的。當初設計Python的時候,考慮在主循環中只能有一個控制線程在執行,就像單核CPU進行多線程編程一樣。
怎么做到這樣控制的呢?就是這里的GIL來控制的,這個鎖用來保證同時只有一個線程在運行。
執行方式:
這幾個細節知識點:
當調用外部代碼(C/C++擴展的內置函數)時, GIL會保持鎖定,知道函數執行結束
對于面向I/O的Python例程,GIL會在I/O調用前被釋放,從而允許其他線程在I/O執行期間運行
如果是針對計算密集型的操作代碼,該線程整個時間片內更傾向于始終占有處理器和GIL。
所以,針對Python虛擬機單線程(GIL)的設計原因,只有線程在執行I/O密集型的應用,才能更好的發揮Python的并發性。
對比thread,threading
Python多個模塊可以進行多線程編程,包括:thread,threading等。他們都可以用來創建和管理線程。
thread模塊提供了基本的線程和鎖定支持,而threading模塊提供了更高級別,功能更全面的線程管理。
推薦使用更高級別的threading模塊,下面是一個簡單的對比:
特征要素
thread
threading
功能全面性
基本(偏底層)
全面,高級
守護進程
不支持
支持
線程同步原語
僅1個(Lock)
很多(Lock,Semaphore,Barrier...)
守護進程講解
守護進程一般是一個等待客戶端請求服務的服務器。如果沒有客戶端請求,守護進程一般是空閑的。一般把一個線程設置成守護進程,就表示這個線程是不重要的。所以進程退出時是不需要等待這個守護線程完成的。
但是原先的thread 模塊是不區分守護或者非守護進程的,也就是說當主線程退出的時候,所有子線程都將終止,而不管他們是否仍在工作。如果你不想這種情況發生,那么就可以采用threading模塊。整個Python程序(一般為主線程)將在所有非守護進程退出是才會退出。
設置守護進程,在線程啟動之前設置:thread.daemon = True
多線程實踐
threading實例
方式1:創建一個thread實例,傳遞它一個函數
import threading
from time import sleep, ctime
sleep_times = [4, 2]
def loop(threadNo, sleep_time):
print('Start loop', threadNo, 'at:', ctime())
sleep(sleep_time) #Sleep一段時間
print('loop', threadNo, 'done at:', ctime())
def main():
print('starting at:', ctime())
threads = []
threadIds = range(len(sleep_times))
for i in threadIds:
thread = threading.Thread(target=loop, args=(i,sleep_times[i]))
threads.append(thread)
for t in threads:
# 依次啟動線程
t.start()
for t in threads:
# 等待所有線程完成
t.join() #將等待線程結束
print('all Done at :', ctime())
if __name__ == '__main__':
main()
方式2:派生Thread的子類,并創建子類的實例
import threading
from time import sleep, ctime
sleep_times = [4, 2]
class MyThread(threading.Thread):
def __init__(self, func, args, name=''):
threading.Thread.__init__(self)
self.func = func
self.name = name
self.args = args
def run(self):
self.func(*self.args)
def loop(threadNo, sleep_time):
print('Start loop', threadNo, 'at:', ctime())
sleep(sleep_time) # Sleep一段時間
print('loop', threadNo, 'done at:', ctime())
def main():
print('starting at:', ctime())
threads = [] # 用于存儲所有線程實例的列表
threadIds = range(len(sleep_times))
for i in threadIds:
# 創建線程實例
thread = MyThread(loop, (i, sleep_times[i]))
threads.append(thread)
for t in threads:
# 依次啟動線程
t.start()
for t in threads:
# 等待所有線程完成
t.join() # 將等待線程結束
print('all Done at :', ctime())
if __name__ == '__main__':
main()
thread實例
由于本人使用的python3.6,這個thread已經變成_thread
import _thread
from time import sleep, ctime
sleep_times = [4, 2]
def loop(threadNo, sleep_time, lock):
print('Start loop', threadNo, 'at:', ctime())
sleep(sleep_time) #Sleep一段時間
print('loop', threadNo, 'done at:', ctime())
lock.release() #釋放鎖
def main():
print('starting at:', ctime())
locks = []
threadIds = range(len(sleep_times))
for i in threadIds:
#通過調用_thread.allocate_lock獲得鎖對象
lock = _thread.allocate_lock()
#通過acquire()方法取得鎖
lock.acquire()
locks.append(lock)
for i in threadIds:
# 依次啟動線程
_thread.start_new_thread(loop, (i, sleep_times[i], locks[i]))
for i in threadIds:
# 如果當前的鎖Lock沒有釋放的話,一直循環等待
while locks[i].locked():
pass
print('all Done at :', ctime())
if __name__ == '__main__':
main()
總結
以上是生活随笔為你收集整理的python3多线程编程_Python 3多线程编程学习笔记-基础篇的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 多相机坐标转换_使用KITTI数据集实现
- 下一篇: JDBC练习二