最簡單的啓動線程
import threading
thread = threading.Thread(target = func, args = (1,2,3))
cmdServer.start()
threading.Thread.run() 調用func,threading.Thread.start() 則會調用包含run()的方法。在執行threading.Thread.start()時候,會執行func。
繼承threading.Thread,重寫run()方法
class Task(threading.Thread)
def __init__():
threading.Thread.__init__(self)
def run(self):
'重寫run方法,start啓動的時候會調用run方法'
pass
thread = Task()
thread.satrt()
守護線程
python 線程默認在主線程退出後,子線程還會繼續執行
當將線程設爲守護線程時,在主線程退出後子線程也會一同結束
thread = threading.Thread(target = func, args = (1,2,3))
thread.setDaemon(True)
cmdServer.start()
線程鎖
lock = threading.Lock()
lock.acquire()
pass
lock.release()
python 線程雖然是調用系統線程,但由於GIL(全局解釋鎖),實際使用的還是單核。
python 在線程調度時,是按照執行代碼行數進行調度的,一般每執行100行代碼(可以通過sys.getcheckinterval()獲取),然後開始進行調度,當然調度是隨機的。掛起的線程不參與調度(sleep等)
python 多線程適合處理I/O密集型的業務,當處理CPU密集型的業務時最好使用多進程
隊列
import Queue
maxsize:設置隊列長度,當該值爲空時,默認無限制,當隊列長度達到最大值時,線程put方法會被阻塞,直到長度小於最大值
queue = Queue.Queue(maxsize = 10)
queue.put('item')
item = queue.get()
python 線程隊列默認是阻塞的,可以使用timeout參數設置等待超時時間
queue.put('item', timeout = 10)
item = queue.get(timeout = 10)
而當block參數爲False時,操作隊列變爲非阻塞方式,並忽略timeout參數,會立即操作隊列,如果操作成功,會直接插入/取出數據,否則拋出異常
queue.put('item', block = False, timeout = 10)
item = queue.get(block = False, timeout = 10)
常用方法:
Queue.qsize() 返回隊列的大小
Queue.empty() 如果隊列爲空,返回True,反之False
Queue.full() 如果隊列滿了,返回True,反之False
Queue.get() 獲取隊列,timeout等待時間
Queue.get_nowait() 相當Queue.get(False)
Queue.put(item) 寫入隊列,timeout等待時間
Queue.put_nowait(item) 相當Queue.put(item, False)
Queue.task_done() 在完成一項工作之後,Queue.task_done()函數向任務已經完成的隊列發送一個信號
Queue.join() 實際上意味着等到隊列爲空,再執行別的操作