在本章中,我們將學習如何在Python中實現線程。
用於線程實現的Python模組
Python線程有時稱為羽量級進程,因為線程比進程佔用的記憶體少得多。 線程允許一次執行多個任務。 在Python中,以下兩個模組在一個程式中實現線程 -
_thread
模組threading
模組
這兩個模組之間的主要區別在於_thread
模組將線程視為一個函數,而threading
模組將每個線程視為一個對象並以面向對象的方式實現它。 此外,_thread
模組在低級線程中有效並且比threading
模組具有更少的功能。
_thread 模組
在Python的早期版本中,擁有thread
模組,但在相當長的一段時間裏它已被視為“已棄用”。 鼓勵用戶改用threading
模組。 因此,在Python 3中,thread
模組不再可用。 它已被重命名為_thread
,用於Python3中的向後不相容。
為了在_thread
模組的幫助下生成新的線程,我們需要調用它的start_new_thread
方法。 這種方法的工作可以通過以下語法來理解 -
_thread.start_new_thread ( function, args[, kwargs] )
這裏,
args
是一個參數的元組kwargs
是關鍵字參數的可選字典
如果想在不傳遞參數的情況下調用函數,那麼需要在args
中使用一個空的參數元組。
此方法調用立即返回,子線程啟動,並調用與傳遞的列表(如果有的話)args
的函數。 線程在函數返回時終止。
示例
以下是使用_thread
模組生成新線程的示例。在這裏使用start_new_thread()
方法。
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: unable to start thread")
while 1:
pass
在_thread
模組的幫助下理解新線程的生成。
Thread-1: Mon Apr 23 10:03:33 2018
Thread-2: Mon Apr 23 10:03:35 2018
Thread-1: Mon Apr 23 10:03:35 2018
Thread-1: Mon Apr 23 10:03:37 2018
Thread-2: Mon Apr 23 10:03:39 2018
Thread-1: Mon Apr 23 10:03:39 2018
Thread-1: Mon Apr 23 10:03:41 2018
Thread-2: Mon Apr 23 10:03:43 2018
Thread-2: Mon Apr 23 10:03:47 2018
Thread-2: Mon Apr 23 10:03:51 2018
threading模組
threading
模組以面向對象的方式實現,並將每個線程視為一個對象。 因此,它為線程提供了比_thread
模組更強大,更高層次的支持。該模組包含在Python 2.4中。
threading 模組中的其他方法
threading
模組包含_thread
模組的所有方法,但它也提供了其他方法。 其他方法如下 -
threading.activeCount()
- 此方法返回處於活動狀態的線程對象的數量threading.currentThread()
- 此方法返回調用者線程式控制制中的線程對象數。threading.enumerate()
- 此方法返回當前活動的所有線程對象的列表。
為了實現線程,threading
模組具有提供以下方法的Thread
類 -
run()
-run()
方法是線程的入口點。start()
-start()
方法通過調用run方法來啟動線程。join([time])
-join()
等待線程終止。isAlive()
-isAlive()
方法檢查線程是否仍在執行。getName()
-getName()
方法返回線程的名稱。setName()
-setName()
方法設置線程的名稱。
如何使用 threading 模組創建線程?
在本節中,我們將學習如何使用threading
模組創建線程。 按照以下步驟使用threading
模組創建一個新線程 -
第1步 - 在這一步中,需要定義Thread
類的新子類。
第2步 - 然後為了添加額外的參數,需要重寫__init __(self [,args])
方法。
第3步 - 在這一步中,需要重寫run(self [,args])
方法來實現線程在啟動時應該執行的操作。
現在,在創建新的Thread
子類後,可以創建它的一個實例,然後通過調用start()
來啟動一個新線程,start()
又調用run()
方法。
示例
下麵這個例子演示如何使用threading
模組生成一個新的線程。
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 ("Starting " + self.name)
print_time(self.name, self.counter, 5)
print ("Exiting " + 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 ("Exiting Main Thread")
Starting Thread-1
Starting Thread-2
執行上面示例代碼,得到以下結果 -
Thread-1: Mon Apr 23 10:52:09 2018
Thread-1: Mon Apr 23 10:52:10 2018
Thread-2: Mon Apr 23 10:52:10 2018
Thread-1: Mon Apr 23 10:52:11 2018
Thread-1: Mon Apr 23 10:52:12 2018
Thread-2: Mon Apr 23 10:52:12 2018
Thread-1: Mon Apr 23 10:52:13 2018
Exiting Thread-1
Thread-2: Mon Apr 23 10:52:14 2018
Thread-2: Mon Apr 23 10:52:16 2018
Thread-2: Mon Apr 23 10:52:18 2018
Exiting Thread-2
Exiting Main Thread
帶有線程狀態的Python程式
有五種線程狀態 - 新的,可運行,運行,等待和死亡。 在這五個中,我們將主要關注三個狀態 - 運行,等待和死亡。 一個線程獲取處於運行狀態的資源,等待處於等待狀態的資源; 如果執行和獲取的資源的最終版本處於死亡狀態。
下麵的Python程式在start()
,sleep()
和join()
方法的幫助下將分別顯示線程是如何進入運行,等待和死亡狀態的。
第1步 - 導入必要的模組,threading
和time
import threading
import time
第2步 - 定義一個函數,它將在創建線程時調用。
def thread_states():
print("Thread entered in running state")
第3步 - 使用time
模組的sleep()
方法讓線程等待2秒鐘。
time.sleep(2)
第4步 - 現在,創建一個名為T1
的線程,它接受上面定義的函數的參數。
T1 = threading.Thread(target=thread_states)
第5步 - 現在,使用start()
函數,可以開始啟動線程。 它會產生這個資訊,這個資訊是在定義函數時設定的。
T1.start()
# Thread entered in running state
第6步 - 現在,最後可以在完成執行後使用join()
方法終止線程。
T1.join()
在Python中啟動一個線程
在python中,可以通過不同的方式啟動一個新的線程,但其中最簡單的一個就是將其定義為一個單一的函數。 在定義函數之後,可以將它作為新線程的目標。線程對象等等。 執行下麵的Python代碼來理解函數的工作原理 -
import threading
import time
import random
def Thread_execution(i):
print("Execution of Thread {} started\n".format(i))
sleepTime = random.randint(1,4)
time.sleep(sleepTime)
print("Execution of Thread {} finished".format(i))
for i in range(4):
thread = threading.Thread(target=Thread_execution, args=(i,))
thread.start()
print("Active Threads:" , threading.enumerate())
執行上面代碼,得到以下結果 -
Execution of Thread 0 started
Active Threads:
[<_MainThread(MainThread, started 6040)>,
<HistorySavingThread(IPythonHistorySavingThread, started 5968)>,
<Thread(Thread-3576, started 3932)>]
Execution of Thread 1 started
Active Threads:
[<_MainThread(MainThread, started 6040)>,
<HistorySavingThread(IPythonHistorySavingThread, started 5968)>,
<Thread(Thread-3576, started 3932)>,
<Thread(Thread-3577, started 3080)>]
Execution of Thread 2 started
Active Threads:
[<_MainThread(MainThread, started 6040)>,
<HistorySavingThread(IPythonHistorySavingThread, started 5968)>,
<Thread(Thread-3576, started 3932)>,
<Thread(Thread-3577, started 3080)>,
<Thread(Thread-3578, started 2268)>]
Execution of Thread 3 started
Active Threads:
[<_MainThread(MainThread, started 6040)>,
<HistorySavingThread(IPythonHistorySavingThread, started 5968)>,
<Thread(Thread-3576, started 3932)>,
<Thread(Thread-3577, started 3080)>,
<Thread(Thread-3578, started 2268)>,
<Thread(Thread-3579, started 4520)>]
Execution of Thread 0 finished
Execution of Thread 1 finished
Execution of Thread 2 finished
Execution of Thread 3 finished
在Python中啟動一個線程
在python中,可以通過不同的方式啟動一個新的線程,但最簡單的就是將其定義為一個單一的函數。 在定義函數之後,可以將它作為新線程的目標。線程對象等等。 執行下麵的Python代碼來理解函數的工作原理 -
import threading
import time
def nondaemonThread():
print("starting my thread")
time.sleep(8)
print("ending my thread")
def daemonThread():
while True:
print("Hello")
time.sleep(2)
if __name__ == '__main__':
nondaemonThread = threading.Thread(target = nondaemonThread)
daemonThread = threading.Thread(target = daemonThread)
daemonThread.setDaemon(True)
daemonThread.start()
nondaemonThread.start()
在上面的代碼中,有兩個函數,分別是- nondaemonThread()
和daemonThread()
。 第一個函數列印其狀態並在8秒後休眠,而deamonThread()
函數每2秒無限期地列印出Hello。 我們可以通過以下輸出來瞭解nondaemon
和daemon
線程之間的區別 -
Hello
starting my thread
Hello
Hello
Hello
Hello
ending my thread
Hello
Hello
Hello
Hello
Hello