python threading 模塊使用多線程。感謝小馬哥指點迷津。
#!/usr/bin/env python # -*- coding: UTF-8 -*- import threading threads = [] # 先創建線程對象 for li in db_con: t = threading.Thread(target=update_thread,args=(list,file,db_con,li)) threads.append(t) # 啓動所有線程 for i in (0,len(threads)): threads[i].start() #阻塞主線程,直到所有線程完成或超時後執行主線程。參數說明中有解釋。 for i in (0,len(threads)): threads[i].join() def update_thread(list,file,db_con,li): ## do something
參數說明:
def __init__(self, group=None, target=None, name=None, args=(), kwargs={})
參數group是預留的,用於將來擴展;
參數target是一個可調用對象(也稱爲活動[activity]),在線程啓動後執行;
參數name是線程的名字。默認值爲“Thread-N“,N是一個數字。
參數args和kwargs分別表示調用target時的參數列表和關鍵字參數。
Thread.join([timeout])
調用Thread.join將會使主調線程堵塞,直到被調用線程運行結束或超時。參數timeout是一個數值類型,表示超時時間,如果未提供該參數,那麼主調線程將一直堵塞到被調線程結束
例:
#!/usr/bin/env python # -*- coding: UTF-8 -*- import threading, time def doWaiting(): print 'start waiting:', time.strftime('%H:%M:%S') time.sleep(3) print 'stop waiting', time.strftime('%H:%M:%S') thread1 = threading.Thread(target = doWaiting) thread1.start() time.sleep(1) #確保線程thread1已經啓動 print 'start join' thread1.join() #將一直堵塞,直到thread1運行結束。 print 'end join'
網上找到一個經典案例。
鏈接地址:http://www.jb51.net/article/53918.htm
#-*- encoding: gb2312 -*- import threading import time class Test(threading.Thread): def __init__(self, num): threading.Thread.__init__(self) self._run_num = num def run(self): global count, mutex threadname = threading.currentThread().getName() for x in xrange(0, int(self._run_num)): mutex.acquire() count = count + 1 mutex.release() print threadname, x, count time.sleep(1) if __name__ == '__main__': global count, mutex threads = [] num = 4 count = 1 # 創建鎖 mutex = threading.Lock() # 創建線程對象 for x in xrange(0, num): threads.append(Test(10)) # 啓動線程 for t in threads: t.start() # 等待子線程結束 for t in threads: t.join()