如何在Python中使用線程?我試圖理解Python中的線程。我看過文檔和示例,但坦率地說,很多例子都過于復雜,我很難理解它們。你如何清楚地展示為多線程劃分的任務?
4 回答

qq_花開花謝_0
TA貢獻1835條經驗 獲得超7個贊
注意:對于Python中的實際并行化,您應該使用多處理模塊來并行執行并行執行的多個進程(由于全局解釋器鎖定,Python線程提供交錯但實際上是串行執行,而不是并行執行,并且僅在交錯I / O操作)。
但是,如果您只是在尋找交錯(或者正在進行可以并行化的I / O操作,盡管全局解釋器鎖定),那么線程模塊就是起點。作為一個非常簡單的例子,讓我們通過并行求和子范圍來考慮求和大范圍的問題:
import threadingclass SummingThread(threading.Thread): def __init__(self,low,high): super(SummingThread, self).__init__() self.low=low self.high=high self.total=0 def run(self): for i in range(self.low,self.high): self.total+=i thread1 = SummingThread(0,500000)thread2 = SummingThread(500000,1000000)thread1.start() # This actually causes the thread to runthread2 .start()thread1.join() # This waits until the thread has completedthread2.join() # At this point, both threads have completedresult = thread1.total + thread2.totalprint result
請注意,上面是一個非常愚蠢的例子,因為它絕對沒有I / O,并且由于全局解釋器鎖,它將在CPython中以串行方式執行,盡管是交錯的(帶有上下文切換的額外開銷)。
添加回答
舉報
0/150
提交
取消