Python 2.4 之前有 thread 模塊支持多線程編程,2.4 之後新增了 threading 模塊,提供了更高級、更強大的線程支持。
threading 提供了一些模塊級函數:
此外,threading 還提供了許多與 Java 中 Thread 類相似的方法(注意:以下都是實例方法):
創建線程有兩種方式:
1)繼承 threading.Thread
a. 創建一個 threading.Thread 的子類;
b. 覆蓋 init(self [,args]);
c. 重寫 run 方法。
#!/usr/bin/python
#!coding=utf-8
import threading
import time
exitFlag = 0
class MyThread(threading.Thread):
def __init__(self, threadID, name, counter):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
def run(self):
task()
def task(self):
'''線程要執行的任務'''
print 'starting ' + self.name
print 'exiting ' + self.name
# 創建線程
thread1 = MyThread(1, 'Thread-1', 1)
thread2 = MyThread(2, 'Thread-2', 2)
# 啟動線程
thread1.start()
thread2.start()
# 等待線程結束
thread1.join()
thread2.join()
print 'exiting main thread'
2)把任務函數作為參數傳給 Thread
threading.Thread(target=task, args=()).start()
這種方式更為簡潔,直接把要執行的函數與參數傳入即可,適合任務邏輯簡單的場景。