Python線程創建與使用


    Python多為線程編程提供了兩個簡單明了的模塊:thread和threading,Python3中已經不存thread模塊,已經被改名為_thread,實際優先使用

threading模塊。

1.Python創建線程的兩種方法:

①:創建一個threading.Thread對象,在其初始化函數中將可調用對象作為參數傳入 

import threading
def handle(sid):
   print("Thread %d run"%sid)

#創建線程方法1
for i in range(1, 11):
    t = threading.Thread(target=handle, args=(i,))
    t.start()
print("main thread")

②:通過繼承Thread類,重寫它的run()方法

import threading
def handle(sid):
   print("Thread %d run"%sid)
class MyThread(threading.Thread):
    def __init__(self,sid):
        threading.Thread.__init__(self)
        self.sid = sid
    def run(self):
        handle(self.sid)

for i in range(1,11):
    t = MyThread(i)
    t.start()
print("main thread")

2.threading.Thread對象:

class threading.Thread(group=None, target=None, name=None, args=(), kwargs={}, *, daemon=None)
group :這個應該為空,是個保留位,是為了以后ThreadGroup(線程組)這個類實現而預留的
target:是個由run()方法執行調用的可調用對象,也就是線程要執行的函數,默認為空,意味着沒有東西可以被調用
name: 這個參數表示線程的名稱,默認情況下,是一個類似於Thread-N形式的名字,這里的N是小的十進制失蹤
args: 這是個參數元組,是用來給target調用的,默認為一個空的元組
kwargs={} : 這是個關鍵字參數組成的字典,是用來給target調用的,默認為一個空的字典
daemon 這個bool值表明這個線程是否是守護進程,當為True時,就是個守護進程,否則為False,就不是守護進程

這個必須在start()之前被設置,否則就會拋出RuntimeError異常,它的初始值繼承於創建它的線程,如果主進程不是守護進程,
那么由主進程創建的子進程默認都不是守護進程

3.start方法與run方法

啟動線程是調用start方法,而不調用run方法,這里兩者有什么區別呢
首先線程的狀態有五種:創建、就緒、運行、阻塞和死亡
當調用start函數,線程的狀態就處於就緒狀態,處於就緒狀態后,還需要等待CPU分配時間片
如果分到時間片,就進入運行狀態,執行run函數

start() --> 啟動線程,這個函數只能在一個線程中調用一次,如果超過一次則會拋出RuntimeError異常,它安排run()方法在另一個線程中調用

run() -->  用以表示線程活動的方法,你可以在子線程中覆蓋此方法

import threading
class MyThread(threading.Thread):
    def __init__(self,sid):
        threading.Thread.__init__(self)
        self.sid = sid
    def run(self):
        currentTreadname = threading.currentThread()
        print("running in", currentTreadname)

t = MyThread(1)
t.start()
t.run()

輸出結果:

running in <MyThread(Thread-1, started 4948)>
running in <_MainThread(MainThread, started 5276)>

可以看到調用start方法是在創建的子線程中調用,而直接調用run方法則是在主線程中調用


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM