首頁  >  文章  >  後端開發  >  Python多執行緒

Python多執行緒

高洛峰
高洛峰原創
2016-11-23 13:59:571137瀏覽

多執行緒類似同時執行多個不同程序,多執行緒執行有以下優點:

使用執行緒可以把佔據長時間的程式中的任務放到後台去處理。

用戶介面可以更加吸引人,這樣例如用戶點擊了一個按鈕去觸發某些事件的處理,可以彈出一個進度條來顯示處理的進度

程序的運行速度可能加快

在一些等待的任務實現上如使用者輸入、檔案讀寫和網路收發資料等,執行緒就比較有用了。在這種情況下我們可以釋放一些珍貴的資源如記憶體佔用等等。

執行緒在執行過程中與進程還是有區別的。每個獨立的執行緒都有一個程式運行的入口、順序執行序列和程式的出口。但是執行緒不能夠獨立執行,必須依存在應用程式中,由應用程式提供多個執行緒執行控制。

每個執行緒都有他自己的一組CPU暫存器,稱為執行緒的上下文,該上下文反映了執行緒上次運行該執行緒的CPU暫存器的狀態。

指令指標和堆疊指標暫存器是執行緒上下文中兩個最重要的暫存器,執行緒總是在進程得到上下文中運行的,這些位址都用於標誌擁有執行緒的進程位址空間中的記憶體。

線程可以被搶佔(中斷)。

在其他執行緒正在運行時,執行緒可以暫時擱置(也稱為睡眠) -- 這就是執行緒的退讓。

 

開始學習Python執行緒

Python中使用執行緒有兩種方式:函數或用類別來包裝執行緒物件。

函數式:呼叫thread模組中的start_new_thread()函數來產生新執行緒。文法如下:

thread.start_new_thread ( function, args[, kwargs] )

   

:5

函數。

args - 傳遞給執行緒函數的參數,他必須是個tuple類型。

kwargs - 可選參數。

實例:

#!/usr/bin/python

 

import thread

import 

import thread

import 

為一個函數定義一個函數為一個_time( threadName, delay):

count = 0

   while count       time.sleep(delay)

    % ( threadName, time.ctime(time.time()) )

 

# 建立兩個執行緒

try:

   thread.start_new_thread( print_time, ("Thread-1",  ) )

. 4, ) )

except:

   print "Error: unable to start thread"

 

while 1:如下:

Thread-1: Thu Jan 22 15:42:17 2009

Thread-1: Thu Jan 22 15:42:19 2009

Thread-2: ThuJancom 22 15:42: 21 2009

Thread-2: Thu Jan 22 15:42:23 2009

Thread-1: Thu Jan 22 15:42:23 20915 5 2009

Thread -2: Thu Jan 22 15:42:27 2009

Thread-2: Thu Jan 22 15:42:31 2009

線程的結束一般依賴執行緒函數的自然結束;也可以在執行緒函數中呼叫thread.exit(),他拋出SystemExit exception,達到退出執行緒的目的。

執行緒模組

Python透過兩個標準函式庫thread和threading提供對執行緒的支援。 thread提供了低階的、原始的執行緒以及一個簡單的鎖。

thread 模組提供的其他方法:

threading.currentThread(): 傳回目前的執行緒變數。

threading.enumerate(): 傳回一個包含正在執行的執行緒的list。正在執行指執行緒啟動後、結束前,不包含啟動前和終止後的執行緒。

threading.activeCount(): 傳回正在執行的執行緒數量,與len(threading.enumerate())有相同的結果。

除了使用方法外,線程模組同樣提供了Thread類別來處理線程,Thread類別提供了以下方法:

run(): 用以表示線程活動的方法。

start():啟動執行緒活動。

 

join([time]): 等待至執行緒中止。這阻塞調用線程直至線程的join() 方法被調用中止-正常退出或拋出未處理的異常-或者是可選的超時發生。

isAlive(): 返回執行緒是否活動的。

getName(): 傳回執行緒名稱。

setName(): 設定執行緒名。

使用Threading模組建立執行緒

使用Threading模組建立線程,直接從threading.Thread繼承,然後重寫__init__方法和run方法:

#!/usr/python

import threading

import time

 

exitFlag = 0

 

class myThread __init__(self, threadID, name, counter):

        threading .Thread.__init__(self)

        self.threadID = threadID

        

    def run(self):                   #將要執行的程式寫到run功能之後會直接執行run函數 

        print "Starting " + self.name

        print_time(self. "Exiting " + self.name

 

def print_time(threadName, delay , counter):

    while counter:

        if exitFlag:

     time.sleep(delay)

        print "%s: %s" % (threadName, time.ctime(time.time ()))

        counter -= 1

 

# 創建新執行緒

thread1 = myThread(1, 創建新執行緒

thread1 = myThread(1, 創建新主題read-2", 2)

 

# 開啟執行緒

thread1.start()

thread2.start()

 

print "Exiting Main

 

print "Exiting Mainin

 

Starting因此

Thread-2: Thu Mar 21 09:10:04 2013

Thread-1: Thu Mar 21 09:10:05 2013

 Mar 21 09: 10:06 2013

Thread-1: Thu Mar 21 09:10:07 2013

Exiting Thread 21 09:10:07 2013

Exiting Thread  Thu Mar 21 09 :10:10 2013

Thread-2: Thu Mar 21 09:10:12 2013

Exiting 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的尷尬場面。

實例:

#!/usr/bin/python

 

import threading

import time

 

class myThread (threading.Thread):

    def __init__(self, threadID, name, count .        self.threadID = threadID

        self.name = name

        self.counter = counter

    def run(self):

      # 取得鎖定,成功取得鎖定後返回True

       # 可選擇的timeout參數不填時將一直阻塞直到鎖定

       # 否則逾時後將返回False

        threadLock.acquire()

.        # 釋放鎖定

        threadLock.release()

 

def print_time(threadName, delay, counter):

    while counter:

        time) time.ctime(time.time()))

        counter -= 1

 

threadLock = threading.Lock()

threads = []

 

#com

thread2 = myThread( 2, "Thread-2", 2)

 

# 開啟新執行緒

thread1.start()

thread2.start()

 

threads.append(thread2)

 

# 等待所有執行緒完成

for t in threads:

   

執行緒優先權佇列( 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() 取得佇列,timeout等待時間

Queue.get_nowait() 相當

Queue.put(item) 寫入隊列,timeout等待時間

Queue.put_nowait(item) 相當Queue.put(item, False)

Queue.task_done() 在完成一項工作之後,Queue.task_Queue.task_done() 在完成一項工作之後,Queue.task_Queue.task_done() 在完成一項工作之後,Queue.函數向任務已經完成的佇列發送一個訊號

Queue.join() 實際上意味著等到佇列為空,再執行別的操作

實例:

#!/usr/bin/python

 

import Queue

import threading

import time

 

exitFlag  003533    def __init__(self, threadID, name, q):

        threading. Thread.__init__(self)

        self.threadID = threadID

       

    def run(self):

        print "Starting " + self.name

     .name, self.q)

        print "Exiting " + self.name

 

def process_data(readthread)

 

        queueLock.acquire()

        if not workQueue.empty( ):

            data = q.get()

           

            print "%s processing %s" % (threadName, data)

    .release()

        time.sleep(1)

 

threadList = ["Thread-1", "Thread- 2", "Thread-3"]

nameList = ["One", "Two", "Three", "Four", "Five"]

queueLock =com (10)

threads = []

threadID = 1

 

# 建立新執行緒

for tName in threadList# 建立新主題

for tName in threadList# 建立新主題

for tName in workQueue)

    thread.start()

threads.append(thread)

    threadID += 1

 

# 填充隊列

queueLock.

queueLock.release()

# 等待佇列清空

while not workQueue.empty():

    pass

 

 等待所有執行緒完成

for t in threads:

    t.join()

print "Exiting Main Thread"

   

2

Starting Thread-3

Thread- 1 processing One

Thread-2 processing Two

Thread-3 processing Three

Thread-1 processing Four

素-Thcom ing Thread-1

Exiting Thread-2

Exiting Main Thread

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
上一篇:python XML解析下一篇:python XML解析