Python基礎 多執行緒

2021-08-03 02:20:58 字數 2287 閱讀 9420

多工可以由多程序完成,也可以由乙個程序內的多執行緒完成。

我們前面提到了程序是由若干執行緒組成的,乙個程序至少有乙個執行緒。

由於執行緒是作業系統直接支援的執行單元,因此,高階語言通常都內建多執行緒的支援,python也不例外,並且,python的執行緒是真正的posix thread,而不是模擬出來的執行緒。

python的標準庫提供了兩個模組:_thread和threading,_thread是低階模組,threading是高階模組,對_thread進行了封裝。絕大多數情況下,我們只需要使用threading這個高階模組。

啟動乙個執行緒就是把乙個函式傳入並建立thread例項,然後呼叫start()開始執行:

import time, threading, random

#執行緒執行**

defloop

(msg):

print(msg)

print('thread %s is running...' % threading.current_thread().name)

n = 0

while n < 5:

n = n + 1

print('thread %s >> %s ' % (threading.current_thread().name, n))

time.sleep(random.random() * 1)

print('thread %s is ended' % threading.current_thread().name)

if __name__=='__main__':

print('thread %s is running...' % threading.current_thread().name)

#執行緒執行的**塊 引數 執行緒名稱

t = threading.thread(target=loop, args=('test',), name='loopthread')

t.start() #開啟執行緒

t.join() #等待執行緒結束

print('thread %s is ended' % threading.current_thread().name)

#列印結果

thread mainthread is running...

test

thread loopthread is running...

thread loopthread >> 1

thread loopthread >> 2

thread loopthread >> 3

thread loopthread >> 4

thread loopthread >> 5

thread loopthread is ended

thread mainthread is ended

由於任何程序預設就會啟動乙個執行緒,我們把該執行緒稱為主線程,主線程又可以啟動新的執行緒,python的threading模組有個current_thread()函式,它永遠返回當前執行緒的例項。主線程例項的名字叫mainthread,子執行緒的名字在建立時指定,我們用loopthread命名子執行緒。名字僅僅在列印時用來顯示,完全沒有其他意義,如果不起名字python就自動給執行緒命名為thread-1,thread-2……

執行緒鎖是為了解決多執行緒情況下的資源讀寫的問題。

resources

lock = threading.lock()

defrun_thread

():# 先要獲取鎖

lock.acquire()

try:

# 修改資源等操作

change_it(resources)

finally:

# 釋放鎖

lock.release()

當多個執行緒同時執行lock.acquire()時,只有乙個執行緒能成功地獲取鎖,然後繼續執行**,其他執行緒就繼續等待直到獲得鎖為止。

獲得鎖的執行緒用完後一定要釋放鎖,否則那些苦苦等待鎖的執行緒將永遠等待下去,成為死執行緒。所以我們用try…finally來確保鎖一定會被釋放。

python的gil

這裡有乙個部落格很不錯,強烈推薦看一下:

說白了還是python的多執行緒還是有很多限制,就算是多程序也不能很好地解決很多問題。

多執行緒程式設計,模型複雜,容易發生衝突,必須用鎖加以隔離,同時,又要小心死鎖的發生。

python直譯器由於設計時有gil全域性鎖,導致了多執行緒無法利用多核。多執行緒的併發在python中就是乙個美麗的夢(目前是這樣)。

Python基礎 多執行緒

多執行緒在程式開發過程中特別重要,我們往往把一些耗時的操作在子執行緒中執行,這就是所謂的多執行緒了。在c 11中,寫了一些關於多執行緒的部落格。python也不例外,當然也要有多執行緒了。python提供了兩個模組來實現多執行緒thread 和threading thread 有一些缺點,在thre...

python 多執行緒基礎

join 等待某執行緒結束在繼續執行 queue 儲存程序結果 執行緒鎖在cpython中存在gil,大家可以嘗試其他直譯器版本,可能就不會存在gil了 import threadingprint threading.active count 列印已啟用執行緒數print threading.enu...

Python多執行緒基礎學習

python多執行緒用法 1.函式式 呼叫thread模組的start new thread 方法來建立執行緒,例如 thread.start new thread function,args args是函式的引數列表,在python裡用元組表示,如 args1 args2 注意這裡引數必須存在,就...