Python學習筆記(二十八)多線程
阿新 • • 發佈:2017-08-19
oop 模擬 筆記 標準庫 函數 只需要 pre 開始 print
摘抄自:https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/00143192823818768cd506abbc94eb5916192364506fa5d000
多任務可以由多進程完成,也可以由一個進程內的多線程完成。
我們前面提到了進程是由若幹線程組成的,一個進程至少有一個線程。
由於線程是操作系統直接支持的執行單元,因此,高級語言通常都內置多線程的支持,Python也不例外,並且,Python的線程是真正的Posix Thread,而不是模擬出來的線程。
Python的標準庫提供了兩個模塊:_thread
和 threading
,_thread
是低級模塊,threading
是高級模塊,對_thread
進行了封裝。絕大多數情況下,我們只需要使用threading
這個高級模塊。
啟動一個線程就是把一個函數傳入並創建Thread
實例,然後調用start()
開始執行:
import time, threading
# 新線程執行的代碼:
def loop():
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(1)
print(‘thread %s ended.‘ % threading.current_thread().name)
print(‘thread %s is running...‘ % threading.current_thread().name)
t = threading.Thread(target=loop, name=‘LoopThread ‘)
t.start()
t.join()
print(‘thread %s ended.‘ % threading.current_thread().name)
Python學習筆記(二十八)多線程