Python底層執行緒API


Python庫中的`_thread`模組提供了一個低階介面,用於處理共享全域性資料空間的輕量級程序的多執行緒。為了同步,此模組中定義了簡單的鎖(也稱為互斥鎖或二元訊號量)。內建的`threading`模組在此模組之上構建了一個更高級別的執行緒API。

start_new_thread()

此模組級函式用於在當前程序中開啟一個新執行緒。該函式將函式物件作為引數。在新執行緒成功建立後,將呼叫此函式。此函式的跨度對應於執行緒的生命週期。可以透過呼叫sleep()函式來阻塞執行緒。

以下程式碼是使用_thread模組的執行緒機制的簡單示例。

import _thread
import time

def run( threadName):
   count = 0
   for i in range(1,6):
      time.sleep(5)
      print ( threadName, i )

_thread.start_new_thread( run, ("child", ) )

for i in range(1,6):
   print ( 'main', i )
   time.sleep(5)

start_new_thread()函式產生一個新執行緒,該執行緒並行呼叫run函式。run()函式以及程式的主執行緒中都有一個迴圈。兩個執行緒中對sleep()函式的呼叫都會導致重疊執行,如下所示:

main 1
child 1
main 2
child 2
main 3
child 3
main 4
child 4
main 5
child 5

執行緒間同步是透過使用Lock物件實現的。allocate_lock()函式返回鎖物件。它有以下方法:

acquire()

此方法無條件地獲取鎖,直到另一個執行緒釋放它為止。一次只有一個執行緒可以獲取鎖。如果成功獲取鎖,則返回值為True,否則為False。

release()

此方法釋放鎖。鎖必須先前已被獲取,但不一定是由同一個執行緒獲取的。

在下面的示例中,聲明瞭兩個執行緒。每個執行緒併發地呼叫run()函式。其中一個執行緒獲取鎖並繼續進入“synchronized”函式,而另一個執行緒等待。

import _thread
import time

def run( threadName):
   lock.acquire()
   synchronized(threadName)
   lock.release()

def synchronized(threadName):
   print (threadName,"has acquired lock")
   counter = 10
   while counter:
      time.sleep(1)
      print ('*', end='')
      counter = counter-1
      print('\n{} has released lock'.format( threadName))

lock = _thread.allocate_lock()

_thread.start_new_thread( run, ("t1", ) )
_thread.start_new_thread( run, ("t2", ) )

輸出

>>> t1 has acquired lock
**********
t1 has released lock
t2 has acquired lock
**********
t2 has released lock

更新於:2019年7月30日

515 次瀏覽

啟動您的職業生涯

完成課程後獲得認證

開始學習
廣告