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