python 测试 多线程 _thread和threading模块 线程同步,线程优先级队列
文章目錄
- python 多線程簡介
- Python中使用線程的兩種方式
- 1、函數式
- 示例
- 2、線程模塊
- 示例
- 線程同步
- 示例
- 線程優先級隊列( Queue)【暫時沒用到,沒仔細看】
- 示例
- 其他
- threading.Thread類
- 1、最簡單的線程程序
- 2、while 循環內的線程
- 3、線程退出方法
python 多線程簡介
多線程類似于同時執行多個不同程序,多線程運行有如下優點:
- 使用線程可以把占據長時間的程序中的任務放到后臺去處理。
- 用戶界面可以更加吸引人,這樣比如用戶點擊了一個按鈕去觸發某些事件的處理,可以彈出一個進度條來顯示處理的進度
- 程序的運行速度可能加快
- 在一些等待的任務實現上如用戶輸入、文件讀寫和網絡收發數據等,線程就比較有用了。在這種情況下我們可以釋放一些珍貴的資源如內存占用等等。
線程在執行過程中與進程還是有區別的。每個獨立的進程有一個程序運行的入口、順序執行序列和程序的出口。但是線程不能夠獨立執行,必須依存在應用程序中,由應用程序提供多個線程執行控制。
每個線程都有他自己的一組CPU寄存器,稱為線程的上下文,該上下文反映了線程上次運行該線程的CPU寄存器的狀態。
指令指針和堆棧指針寄存器是線程上下文中兩個最重要的寄存器,線程總是在進程得到上下文中運行的,這些地址都用于標志擁有線程的進程地址空間中的內存。
- 線程可以被搶占(中斷)。
- 在其他線程正在運行時,線程可以暫時擱置(也稱為睡眠) – 這就是線程的退讓。
Python3 線程中常用的兩個模塊為:
- _thread
- threading(推薦使用)
thread 模塊已被廢棄。用戶可以使用 threading 模塊代替。所以,在 Python3 中不能再使用"thread" 模塊。為了兼容性,Python3 將 thread 重命名為 “_thread”。
Python中使用線程的兩種方式
1、函數式
調用thread模塊中的start_new_thread()函數來產生新線程
_thread.start_new_thread ( function, args[, kwargs] )參數說明:
- function - 線程函數。
- args - 傳遞給線程函數的參數,他必須是個tuple類型。
- kwargs - 可選參數。
示例
#!/usr/bin/python3import _thread import time# 為線程定義一個函數 def print_time( threadName, delay):count = 0while count < 5:time.sleep(delay)count += 1print ("%s: %s" % ( threadName, time.ctime(time.time()) ))# 創建兩個線程 try:_thread.start_new_thread( print_time, ("Thread-1", 2, ) )_thread.start_new_thread( print_time, ("Thread-2", 4, ) ) except:print ("Error: 無法啟動線程")while 1:pass結果:
Thread-1: Wed Apr 6 11:36:31 2016 Thread-1: Wed Apr 6 11:36:33 2016 Thread-2: Wed Apr 6 11:36:33 2016 Thread-1: Wed Apr 6 11:36:35 2016 Thread-1: Wed Apr 6 11:36:37 2016 Thread-2: Wed Apr 6 11:36:37 2016 Thread-1: Wed Apr 6 11:36:39 2016 Thread-2: Wed Apr 6 11:36:41 2016 Thread-2: Wed Apr 6 11:36:45 2016 Thread-2: Wed Apr 6 11:36:49 20162、線程模塊
Python3 通過兩個標準庫 _thread 和 threading 提供對線程的支持。
_thread 提供了低級別的、原始的線程以及一個簡單的鎖,它相比于 threading 模塊的功能還是比較有限的。
threading 模塊除了包含 _thread 模塊中的所有方法外,還提供的其他方法:
- threading.currentThread(): 返回當前的線程變量。
- threading.enumerate(): 返回一個包含正在運行的線程的list。正在運行指線程啟動后、結束前,不包括啟動前和終止后的線程。
- threading.activeCount(): 返回正在運行的線程數量,與len(threading.enumerate())有相同的結果。
除了使用方法外,線程模塊同樣提供了Thread類來處理線程,Thread類提供了以下方法:
- run(): 用以表示線程活動的方法。
- start():啟動線程活動。
- join([time]): 等待至線程中止。這阻塞調用線程直至線程的join() 方法被調用中止-正常退出或者拋出未處理的異常-或者是可選的超時發生。
- isAlive(): 返回線程是否活動的。
- getName(): 返回線程名。
- setName(): 設置線程名。
示例
通過直接從 threading.Thread 繼承創建一個新的子類,并實例化后調用 start() 方法啟動新線程,即它調用了線程的 run() 方法:
#!/usr/bin/python3import threading import timeexitFlag = 0class myThread (threading.Thread):def __init__(self, threadID, name, counter):threading.Thread.__init__(self)self.threadID = threadIDself.name = nameself.counter = counterdef run(self):print ("開始線程:" + self.name)print_time(self.name, self.counter, 5)print ("退出線程:" + self.name)def print_time(threadName, delay, counter):while counter:if exitFlag:threadName.exit()time.sleep(delay)print ("%s: %s" % (threadName, time.ctime(time.time())))counter -= 1# 創建新線程 thread1 = myThread(1, "Thread-1", 1) thread2 = myThread(2, "Thread-2", 2)# 開啟新線程 thread1.start() thread2.start() thread1.join() thread2.join() print ("退出主線程")結果:
D:\20191031_tensorflow_yolov3\python\python.exe C:/Users/SIQI/Desktop/test_multiprocessing/test5.py 開始線程:Thread-1 開始線程:Thread-2 Thread-1: Tue Mar 24 14:10:36 2020 Thread-2: Tue Mar 24 14:10:37 2020 Thread-1: Tue Mar 24 14:10:37 2020 Thread-1: Tue Mar 24 14:10:38 2020 Thread-2: Tue Mar 24 14:10:39 2020 Thread-1: Tue Mar 24 14:10:39 2020 Thread-1: Tue Mar 24 14:10:40 2020 退出線程:Thread-1 Thread-2: Tue Mar 24 14:10:41 2020 Thread-2: Tue Mar 24 14:10:43 2020 Thread-2: Tue Mar 24 14:10:45 2020 退出線程:Thread-2 退出主線程Process finished with exit code 0線程同步
如果多個線程共同對某個數據修改,則可能出現不可預料的結果,為了保證數據的正確性,需要對多個線程進行同步。
使用 Thread 對象的 Lock 和 Rlock 可以實現簡單的線程同步,這兩個對象都有 acquire 方法和 release 方法,對于那些需要每次只允許一個線程操作的數據,可以將其操作放到 acquire 和 release 方法之間。如下:
多線程的優勢在于可以同時運行多個任務(至少感覺起來是這樣)。但是當線程需要共享數據時,可能存在數據不同步的問題。
考慮這樣一種情況:一個列表里所有元素都是0,線程"set"從后向前把所有元素改成1,而線程"print"負責從前往后讀取列表并打印。
那么,可能線程"set"開始改的時候,線程"print"便來打印列表了,輸出就成了一半0一半1,這就是數據的不同步。為了避免這種情況,引入了鎖的概念。
鎖有兩種狀態——鎖定和未鎖定。每當一個線程比如"set"要訪問共享數據時,必須先獲得鎖定;如果已經有別的線程比如"print"獲得鎖定了,那么就讓線程"set"暫停,也就是同步阻塞;等到線程"print"訪問完畢,釋放鎖以后,再讓線程"set"繼續。
經過這樣的處理,打印列表時要么全部輸出0,要么全部輸出1,不會再出現一半0一半1的尷尬場面。、
示例
#!/usr/bin/python3import threading import timeclass myThread(threading.Thread):def __init__(self, threadID, name, counter):threading.Thread.__init__(self)self.threadID = threadIDself.name = nameself.counter = counterdef run(self):print("開啟線程: " + self.name)# 獲取鎖,用于線程同步threadLock.acquire()print_time(self.name, self.counter, 3)# 釋放鎖,開啟下一個線程threadLock.release()def print_time(threadName, counter, delay):while counter:time.sleep(delay)print("%s: %s" % (threadName, time.ctime(time.time())))counter -= 1threadLock = threading.Lock() threads = []# 創建新線程 thread1 = myThread(1, "Thread-1", 1) thread2 = myThread(2, "Thread-2", 2)# 開啟新線程 thread1.start() thread2.start()# 添加線程到線程列表 threads.append(thread1) threads.append(thread2)# 等待所有線程完成 for t in threads:t.join() print("退出主線程")結果:
D:\20191031_tensorflow_yolov3\python\python.exe C:/Users/SIQI/Desktop/test_multiprocessing/test5.py 開啟線程: Thread-1 開啟線程: Thread-2 Thread-1: Tue Mar 24 15:16:19 2020 Thread-2: Tue Mar 24 15:16:22 2020 Thread-2: Tue Mar 24 15:16:25 2020 退出主線程Process finished with exit code 0線程優先級隊列( Queue)【暫時沒用到,沒仔細看】
Python 的 Queue 模塊中提供了同步的、線程安全的隊列類,包括FIFO(先入先出)隊列Queue,LIFO(后入先出)隊列LifoQueue,和優先級隊列 PriorityQueue。
這些隊列都實現了鎖原語,能夠在多線程中直接使用,可以使用隊列來實現線程間的同步。
-
Queue 模塊中的常用方法:
-
Queue.qsize() 返回隊列的大小
-
Queue.empty() 如果隊列為空,返回True,反之False
-
Queue.full() 如果隊列滿了,返回True,反之False
-
Queue.full 與 maxsize 大小對應
-
Queue.get([block[, timeout]])獲取隊列,timeout等待時間
-
Queue.get_nowait() 相當Queue.get(False)
-
Queue.put(item) 寫入隊列,timeout等待時間
-
Queue.put_nowait(item) 相當Queue.put(item, False)
-
Queue.task_done() 在完成一項工作之后,Queue.task_done()函數向任務已經完成的隊列發送一個信號
-
Queue.join() 實際上意味著等到隊列為空,再執行別的操作
示例
#!/usr/bin/python3import queue import threading import timeexitFlag = 0class myThread (threading.Thread):def __init__(self, threadID, name, q):threading.Thread.__init__(self)self.threadID = threadIDself.name = nameself.q = qdef run(self):print ("開啟線程:" + self.name)process_data(self.name, self.q)print ("退出線程:" + self.name)def process_data(threadName, q):while not exitFlag:queueLock.acquire()if not workQueue.empty():data = q.get()queueLock.release()print ("%s processing %s" % (threadName, data))else:queueLock.release()time.sleep(1)threadList = ["Thread-1", "Thread-2", "Thread-3"] nameList = ["One", "Two", "Three", "Four", "Five"] queueLock = threading.Lock() workQueue = queue.Queue(10) threads = [] threadID = 1# 創建新線程 for tName in threadList:thread = myThread(threadID, tName, workQueue)thread.start()threads.append(thread)threadID += 1# 填充隊列 queueLock.acquire() for word in nameList:workQueue.put(word) queueLock.release()# 等待隊列清空 while not workQueue.empty():pass# 通知線程是時候退出 exitFlag = 1# 等待所有線程完成 for t in threads:t.join() print ("退出主線程")結果:
開啟線程:Thread-1 開啟線程:Thread-2 開啟線程:Thread-3 Thread-3 processing One Thread-1 processing Two Thread-2 processing Three Thread-3 processing Four Thread-1 processing Five 退出線程:Thread-3 退出線程:Thread-2 退出線程:Thread-1 退出主線程其他
threading.Thread類
Init signature: threading.Thread(group=None,target=None,name=None,args=(),kwargs=None,*,daemon=None, ) Docstring: A class that represents a thread of control. 表示控制線程的類。This class can be safely subclassed in a limited fashion. There are two ways to specify the activity: by passing a callable object to the constructor, or by overriding the run() method in a subclass. 可以通過有限的方式安全地將此類歸為一類。 有兩種指定活動的方法:通過將可調用對象傳遞給構造函數,或通過重寫子類中的run()方法。Init docstring 初始化文檔字符串: This constructor should always be called with keyword arguments. 始終應使用關鍵字參數調用此構造函數。Arguments are:*group* should be None; reserved for future extension when a ThreadGroup class is implemented. * group *應該為None; 當實現ThreadGroup類時保留給以后的擴展。*target* is the callable object to be invoked by the run() method. Defaults to None, meaning nothing is called. * target *是run()方法要調用的可調用對象。 * 默認為None(無),表示不執行任何操作。*name* is the thread name. By default, a unique name is constructed of the form "Thread-N" where N is a small decimal number. * name *是線程名稱。 默認情況下,唯一名稱的格式為“ Thread-N”,其中N是一個小十進制數字。*args* is the argument tuple for the target invocation. Defaults to (). * args *是目標調用的參數元組。 默認為()。*kwargs* is a dictionary of keyword arguments for the target invocation. Defaults to {}. * kwargs *是用于目標調用的關鍵字參數的字典。 默認為{}。If a subclass overrides the constructor, it must make sure to invoke the base class constructor (Thread.__init__()) before doing anything else to the thread. 如果子類覆蓋了構造函數,則必須確保在對線程執行其他任何操作之前調用基類構造函數(Thread .__ init __())。 File: d:\20191031_tensorflow_yolov3\python\lib\threading.py Type: type Subclasses: Timer, _MainThread, _DummyThread, HistorySavingThread, BackgroundJobBase, HBChannel, Heartbeat, ParentPollerUnix, ParentPollerWindows1、最簡單的線程程序
# 最簡單的線程程序 def worker():print("working")print("finished")t = threading.Thread(target=worker, name='worker') # 線程對象 t.start()結果:
working finished2、while 循環內的線程
import threading import timedef worker():while True:time.sleep(1)print("work")print("finished")t = threading.Thread(target = worker, name='worker') # 線程對象t.start()結果:
work work work work #...3、線程退出方法
import threading import timedef worker():count = 0while True:if (count > 5):raise RuntimeError()time.sleep(1)print("working")count += 1t = threading.Thread(target=worker, name='worker') # 線程對象 t.start() print("==END==")結果:
D:\20191031_tensorflow_yolov3\python\python.exe D:/20191031_tensorflow_yolov3/needed/test/test_Intel_realsense/test_多線程.py ==END== working working working working working working Exception in thread worker: Traceback (most recent call last):File "D:\20191031_tensorflow_yolov3\python\lib\threading.py", line 916, in _bootstrap_innerself.run()File "D:\20191031_tensorflow_yolov3\python\lib\threading.py", line 864, in runself._target(*self._args, **self._kwargs)File "D:/20191031_tensorflow_yolov3/needed/test/test_Intel_realsense/test_多線程.py", line 18, in workerraise RuntimeError() RuntimeErrorProcess finished with exit code 0參考文章1:python并發、并行、多線程及安全
參考文章2:【菜鳥教程】Python3 多線程
總結
以上是生活随笔為你收集整理的python 测试 多线程 _thread和threading模块 线程同步,线程优先级队列的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: opencv python destr
- 下一篇: pyrealsense 官方文档 官方d