thread.start_new_thread(function,args[,kwargs])函式原型,其中function引數是你將要呼叫的執行緒函式名稱沒有括號;
args是講傳遞給你的執行緒函式的引數,他必須是個tuple型別;而kwargs是可選的引數,如果沒有引數,也一定是()
import thread
from time import sleep
from time import ctime
loops = [2,4]
defloop
(nloop, nsec, lock):
print
'start loop', nloop, 'at:', ctime()
sleep(nsec)
print
'end loop', nloop, 'at:', ctime()
lock.release()
defmain
():print
'start main at:', ctime()
locks =
nloops = range(len(loops))
for i in nloops:
lock = thread.allocate_lock()
lock.acquire()
for i in nloops:
thread.start_new_thread(loop, (i,loops[i], locks[i]))
for i in nloops:
while locks[i].locked():
pass
print
'end all at:', ctime()
if __name__ == '__main__':
main()
執行結果:
start main at: sat may 07 11:17:43 2016
start loop 0 at:start loop sat may 07 11:17:43 20161
at: sat may 07 11:17:43 2016
end loop 0 at: sat may 07 11:17:45 2016
end loop 1 at: sat may 07 11:17:47 2016
end all at: sat may 07 11:17:47 2016
python 多執行緒thread
python通過thread模組支援多執行緒,語法也很簡潔,現在通過乙個例項來看一下python中的多執行緒 import thread import time 保證只額外啟動乙個執行緒 isrunning false 啟動的時間控制,測試時間是23點44分,所以定的是這個時間,可以用於指定定時任務...
Python多執行緒Thread
import threading import time import random def worker name print name 開始執行.n 0 while true print name 輸出 str n n n 1 t random.randint 0,5 print name 休眠...
python多執行緒使用thread
import sched import threading import time defnew task function,delay time,args 定時任務函式 param function 需要執行的函式 param delay time 延遲多少時間執行 param args 需要給f...