一、簡介
Python中使用執行緒有兩種方式:函式或者用類來包裝執行緒物件,
函式式:呼叫 _thread 模塊中的start_new_thread()函式來產生新執行緒,語法如下:
引數說明:
- function - 執行緒函式,
- args - 傳遞給執行緒函式的引數,他必須是個tuple型別,
- kwargs - 可選引數,
實體:
import _thread
import time
# 為執行緒定義一個函式
def print_time( threadName, delay):
count = 0
while count < 5:
time.sleep(delay)
count += 1
print ("%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
二、執行緒模塊
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 模塊創建執行緒
可以通過直接從 threading.Thread 繼承創建一個新的子類,并實體化后呼叫 start() 方法啟動新執行緒,即它呼叫了執行緒的 run() 方法:
import threading
import time
exitFlag = 0
class myThread (threading.Thread):
def __init__(self, threadID, name, counter):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
def 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 ("退出主執行緒")
四、執行緒同步
如果多個執行緒共同對某個資料修改,則可能出現不可預料的結果,為了保證資料的正確性,需要對多個執行緒進行同步,
使用 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/python3
import threading
import time
class myThread (threading.Thread):
def __init__(self, threadID, name, counter):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
def run(self):
print ("開啟執行緒: " + self.name)
# 獲取鎖,用于執行緒同步
threadLock.acquire()
print_time(self.name, self.counter, 3)
# 釋放鎖,開啟下一個執行緒
threadLock.release()
def print_time(threadName, delay, counter):
while counter:
time.sleep(delay)
print ("%s: %s" % (threadName, time.ctime(time.time())))
counter -= 1
threadLock = 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 ("退出主執行緒")
五、執行緒優先級佇列( Queue)
1、queue佇列
1.python3中的佇列模塊是queue,不是Queue
2.一般涉及到同步,多執行緒之類用到佇列模塊
3.定義了 queue.Queue 類,以及繼承它的 queue.LifoQueue 類 和 queue.PriorityQueue 類 和 queue.SimpleQueue 類
4.分別對應佇列類(FIFO先進先出),LIFO后進先出佇列類,優先佇列,無邊界FIFO簡單佇列類
5.還有兩個例外:隊滿和隊空
2、佇列queue公共方法
'''
學習中遇到問題沒人解答?小編創建了一個Python學習交流群:857662006
尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和PDF電子書!
'''
import queue
#創建基本佇列
#queue.Queue(maxsize=0)創建一個佇列物件(佇列容量),若maxsize小于或者等于0,佇列大小沒有限制
Q=queue.Queue(10)
print(Q)
print(type(Q))
#1.基本方法
print(Q.queue)#查看佇列中所有元素
print(Q.qsize())#回傳佇列的大小
print(Q.empty())#判斷隊空
print(Q.full())#判斷隊滿
#2.獲取佇列,0--5
#Queue.put(item,block = True,timeout = None )將物件放入佇列,阻塞呼叫(block=False拋例外),無等待時間
for i in range(5):
Q.put(i)
# Queue.put_nowait(item)相當于 put(item, False).
#3.讀佇列,0--5
#Queue.get(block=True, timeout=None)讀出佇列的一個元素,阻塞呼叫,無等待時間
while not Q.empty():
print(Q.get())
# Queue.get_nowait()相當于get(False).取資料,如果沒資料拋queue.Empty例外
#4.另兩種涉及等待排隊任務的方法
# Queue.task_done()在完成一項作業后,向任務已經完成的佇列發送一個信號
# Queue.join()阻止直到佇列中的所有專案都被獲取并處理,即等到佇列為空再執行別的操作
3、其他
1.LifoQueue: LIFO后進先出
2.PriorityQueue:優先級佇列,如果資料元素不具有可比性,則可將資料包裝在忽略資料項的類中,僅比較優先級編號
3.SimpleQueue:簡單佇列,無跟蹤任務的功能
六、Queue詳細引數和用法實體
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() 實際上意味著等到佇列為空,再執行別的操作
實體:
import queue
import threading
import time
exitFlag = 0
class myThread (threading.Thread):
def __init__(self, threadID, name, q):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.q = q
def 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 = https://www.cnblogs.com/xxpythonxx/p/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 ("退出主執行緒")
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/494174.html
標籤:Python
