文章目錄
直接用threading.Thread(target=方法名,args=(參數1,參數2, …)) 創建線程
通過實例對比,瞭解thread.daemon和join
普通的線程並非網上一部分文章所說加不加join都一樣,在不添加time.sleep時候可能輸出一樣,但添加time.sleep之後就會發現區別
①一切默認:thread.daemon=False,使用join()但不帶參數
import threading
import time
def Thread_1(num):
print('Thread_1 start')
for i in range(num):
print('1')
time.sleep(3)
print('Thread_1 end')
def Thread_2(num):
print('Thread_2 start')
for i in range(num):
print('2')
time.sleep(3)
print('Thread_2 end')
if __name__ == '__main__':
thread_list = []
thread_1 = threading.Thread(target=Thread_1, args=(3,))
thread_2 = threading.Thread(target=Thread_2, args=(3,))
#thread_1.daemon = True
#thread_2.daemon = True
thread_list.append(thread_1)
thread_list.append(thread_2)
for i in thread_list:
i.start()
for i in thread_list:
i.join()
print('FINISH')
輸出:
②thread.daemon=False,不使用join()
import threading
import time
def Thread_1(num):
print('Thread_1 start')
for i in range(num):
print('1')
time.sleep(3)
print('Thread_1 end')
def Thread_2(num):
print('Thread_2 start')
for i in range(num):
print('2')
time.sleep(3)
print('Thread_2 end')
if __name__ == '__main__':
thread_list = []
thread_1 = threading.Thread(target=Thread_1, args=(3,))
thread_2 = threading.Thread(target=Thread_2, args=(3,))
#thread_1.daemon = True
#thread_2.daemon = True
thread_list.append(thread_1)
thread_list.append(thread_2)
for i in thread_list:
i.start()
#for i in thread_list:
#i.join()
print('FINISH')
輸出:
在thread.daemon=False時候,都會在線程都結束之後才退出
如果設置thread.daemon=True,則主線程執行完畢後自動退出,不會等待子線程的執行結果。而且隨着主線程退出,子線程也消亡。
這個時候join()的作用體現出來了,join的作用是阻塞,當子線程都結束了,主線程纔會結束
①thread.daemon=True,使用join()
import threading
import time
def Thread_1(num):
print('Thread_1 start')
for i in range(num):
print('1')
time.sleep(3)
print('Thread_1 end')
def Thread_2(num):
print('Thread_2 start')
for i in range(num):
print('2')
time.sleep(3)
print('Thread_2 end')
if __name__ == '__main__':
thread_list = []
thread_1 = threading.Thread(target=Thread_1, args=(3,))
thread_2 = threading.Thread(target=Thread_2, args=(3,))
thread_1.daemon = True
thread_2.daemon = True
thread_list.append(thread_1)
thread_list.append(thread_2)
for i in thread_list:
i.start()
for i in thread_list:
i.join()
print('FINISH')
輸出:
②thread.daemon=True,不使用join()
import threading
import time
def Thread_1(num):
print('Thread_1 start')
for i in range(num):
print('1')
time.sleep(3)
print('Thread_1 end')
def Thread_2(num):
print('Thread_2 start')
for i in range(num):
print('2')
time.sleep(3)
print('Thread_2 end')
if __name__ == '__main__':
thread_list = []
thread_1 = threading.Thread(target=Thread_1, args=(3,))
thread_2 = threading.Thread(target=Thread_2, args=(3,))
thread_1.daemon = True
thread_2.daemon = True
thread_list.append(thread_1)
thread_list.append(thread_2)
for i in thread_list:
i.start()
#for i in thread_list:
#i.join()
print('FINISH')
輸出:
join的timeout參數:
- 當設置守護線程時,含義是主線程對於所有子線程等待 子線程個數×timeout 的時間後 殺死該子線程,最後退出程序。所以說,如果有10個子線程,全部的等待時間就是每個timeout的累加和。時間一到,不管任務有沒有完成,直接殺死。
- 沒有設置守護線程時,主線程將會等待timeout的累加和這樣的一段時間,時間一到,主線程結束,但是並沒有殺死子線程,子線程依然可以繼續執行,直到子線程全部結束,程序退出。
爲了方便比較,所有打印都加上時間
①thread.daemon=True,timeout=2.5
import threading
import time
def Thread_1(num):
print('Thread_1 start',time.ctime(time.time()))
for i in range(num):
print('1s',time.ctime(time.time()))
time.sleep(3)
print('1e', time.ctime(time.time()))
print('Thread_1 end',time.ctime(time.time()))
def Thread_2(num):
print('Thread_2 start',time.ctime(time.time()))
for i in range(num):
print('2s',time.ctime(time.time()))
time.sleep(3)
print('2e',time.ctime(time.time()))
print('Thread_2 end',time.ctime(time.time()))
if __name__ == '__main__':
thread_list = []
thread_1 = threading.Thread(target=Thread_1, args=(3,))
thread_2 = threading.Thread(target=Thread_2, args=(3,))
thread_1.daemon = True
thread_2.daemon = True
thread_list.append(thread_1)
thread_list.append(thread_2)
for i in thread_list:
i.start()
for i in thread_list:
i.join(2.5)
print('FINISH',time.ctime(time.time()))
輸出:
從子線程開始,到強制殺死主線程結束耗時2*2.5秒
子線程的sleep是3,所以各運行了兩個循環
②thread.daemon=True,timeout=5
import threading
import time
def Thread_1(num):
print('Thread_1 start',time.ctime(time.time()))
for i in range(num):
print('1s',time.ctime(time.time()))
time.sleep(3)
print('1e', time.ctime(time.time()))
print('Thread_1 end',time.ctime(time.time()))
def Thread_2(num):
print('Thread_2 start',time.ctime(time.time()))
for i in range(num):
print('2s',time.ctime(time.time()))
time.sleep(3)
print('2e',time.ctime(time.time()))
print('Thread_2 end',time.ctime(time.time()))
if __name__ == '__main__':
thread_list = []
thread_1 = threading.Thread(target=Thread_1, args=(3,))
thread_2 = threading.Thread(target=Thread_2, args=(3,))
thread_1.daemon = True
thread_2.daemon = True
thread_list.append(thread_1)
thread_list.append(thread_2)
for i in thread_list:
i.start()
for i in thread_list:
i.join(5)
print('FINISH',time.ctime(time.time()))
輸出:
可見,子線程9秒都運行完了,根據timeout*2=10秒。可見等待時間超過子線程運行時間,子線程結束後主線程不再繼續等待,繼續運行,如果下面無其他代碼也就結束了,如果還有代碼則繼續按順序運行
如打印FINISH後再加一段代碼運行效果如下:
參數傳遞:摘自runoob教程
使用類繼承創建以及補充的知識
摘自:runoob教程
零碎知識:
python的多線程可以使用_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 通過繼承創建
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() #測試時本機顯示threadName無exit函數,可以改用exit(0)
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-1
開始線程:Thread-2
Thread-1: Wed Apr 6 11:46:46 2016
Thread-1: Wed Apr 6 11:46:47 2016
Thread-2: Wed Apr 6 11:46:47 2016
Thread-1: Wed Apr 6 11:46:48 2016
Thread-1: Wed Apr 6 11:46:49 2016
Thread-2: Wed Apr 6 11:46:49 2016
Thread-1: Wed Apr 6 11:46:50 2016
退出線程:Thread-1
Thread-2: Wed Apr 6 11:46:51 2016
Thread-2: Wed Apr 6 11:46:53 2016
Thread-2: Wed Apr 6 11:46:55 2016
退出線程:Thread-2
退出主線程
線程同步
線程同步:
如果多個線程共同對某個數據修改,則可能出現不可預料的結果,爲了保證數據的正確性,需要對多個線程進行同步。
使用 Thread 對象的 Lock 和 Rlock 可以實現簡單的線程同步,這兩個對象都有 acquire 方法和 release 方法,對於那些需要每次只允許一個線程操作的數據,可以將其操作放到 acquire 和 release 方法之間。如下:
多線程的優勢在於可以同時運行多個任務(至少感覺起來是這樣)。但是當線程需要共享數據時,可能存在數據不同步的問題。
考慮這樣一種情況:一個列表裏所有元素都是0,線程"set"從後向前把所有元素改成1,而線程"print"負責從前往後讀取列表並打印。
那麼,可能線程"set"開始改的時候,線程"print"便來打印列表了,輸出就成了一半0一半1,這就是數據的不同步。爲了避免這種情況,引入了鎖的概念。
鎖有兩種狀態——鎖定和未鎖定。每當一個線程比如"set"要訪問共享數據時,必須先獲得鎖定;如果已經有別的線程比如"print"獲得鎖定了,那麼就讓線程"set"暫停,也就是同步阻塞;等到線程"print"訪問完畢,釋放鎖以後,再讓線程"set"繼續。
經過這樣的處理,打印列表時要麼全部輸出0,要麼全部輸出1,不會再出現一半0一半1的尷尬場面。
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 ("退出主線程")
開啓線程: Thread-1
開啓線程: Thread-2
Thread-1: Wed Apr 6 11:52:57 2016
Thread-1: Wed Apr 6 11:52:58 2016
Thread-1: Wed Apr 6 11:52:59 2016
Thread-2: Wed Apr 6 11:53:01 2016
Thread-2: Wed Apr 6 11:53:03 2016
Thread-2: Wed Apr 6 11:53:05 2016
退出主線程
線程優先級隊列( 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() 實際上意味着等到隊列爲空,再執行別的操作
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 = 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
退出主線程
for t in threads:
t.join()
記得要用join,雖然有 等待隊列清空和exitFlag通知是否結束進程的控制,但最好還是加上join,這得看對代碼有沒有影響了
下面給出一個不加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 = q.get()
queueLock.release()
print ("%s processing %s,%s" % (threadName, data,time.ctime(time.time())))
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)
print("ID:",threadID,time.ctime(time.time()))
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 ("退出主線程")
輸出:
提前開始運行print 退出主線程的代碼(如果下面還有代碼可以理解爲程序繼續往下運行)