thread.start_new_thread(function,args[,kwargs])函數原型,其中function參數是你將要調用的線程函數名稱沒有括號;
args是講傳遞給你的線程函數的參數,他必須是個tuple類型;而kwargs是可選的參數,如果沒有參數,也一定是()
import thread
from time import sleep
from time import ctime
loops = [2,4]
def loop(nloop, nsec, lock):
print 'start loop', nloop, 'at:', ctime()
sleep(nsec)
print 'end loop', nloop, 'at:', ctime()
lock.release()
def main():
print 'start main at:', ctime()
locks = []
nloops = range(len(loops))
for i in nloops:
lock = thread.allocate_lock()
lock.acquire()
locks.append(lock)
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