Python 程式設計/執行緒
外觀
Python 中的執行緒用於同時執行多個執行緒(任務、函式呼叫)。注意,這並不意味著它們在不同的 CPU 上執行。如果程式已經使用 100% 的 CPU 時間,Python 執行緒將不會使你的程式更快。在這種情況下,你可能需要考慮並行程式設計。如果你對使用 Python 進行並行程式設計感興趣,請檢視 此處。
Python 執行緒用於在執行任務涉及一些等待時。一個例子是與另一個計算機上託管的服務進行互動,例如 Web 伺服器。執行緒允許 Python 在等待時執行其他程式碼;這可以透過 sleep 函式輕鬆模擬。
建立一個執行緒,列印從 1 到 10 的數字,並在每次列印之間等待一秒鐘
import threading
import time
def loop1_10():
for i in range(1, 11):
time.sleep(1)
print(i)
threading.Thread(target=loop1_10).start()
#!/usr/bin/env python
import threading
import time
class MyThread(threading.Thread):
def run(self): # Default called function with mythread.start()
print("{} started!".format(self.getName())) # "Thread-x started!"
time.sleep(1) # Pretend to work for a second
print("{} finished!".format(self.getName())) # "Thread-x finished!"
def main():
for x in range(4): # Four times...
mythread = MyThread(name = "Thread-{}".format(x)) # ...Instantiate a thread and pass a unique ID to it
mythread.start() # ...Start the thread, run method will be invoked
time.sleep(.9) # ...Wait 0.9 seconds before starting another
if __name__ == '__main__':
main()
輸出如下所示
Thread-0 started! Thread-1 started! Thread-0 finished! Thread-2 started! Thread-1 finished! Thread-3 started! Thread-2 finished! Thread-3 finished!