join函数
join()会等到调用了该函数的线程执行完后再去执行接下来的代码。比如:
import threading
from time import ctime ,sleep
loops = [2,4]
def loop(nloop , nsce):
print 'start loop:',nloop,'at:',ctime()
sleep(nsce)
print 'loop:',nloop,'at:',ctime()
def main():
print 'start at:',ctime()
threads = []
nloops = range(len(loops))
for i in nloops:
t = threading.Thread(target=loop,args=(i,loops[i]))
threads.append(t)
print 'append'
for i in nloops:
threads[i].start()
print 'start'
for i in nloops:
threads[i].join()
print 'join'
print 'all done at:',ctime()
if __name__ == '__main__':
main()
上面代码中会等到loop0和loop1执行完其任务后再执行print ’ join ‘。
Once threads are started, they will execute until their given function completes, whereby they will exit. If your main thread has things to do other than wait for threads to complete (such as other processing or waiting for new client requests), it should by all means do so. join() is useful only when you want to wait for thread completion.
threading包的使用:
- callable function:
import threading
from time import ctime ,sleep
loops = [2,4]
def loop(nloop , nsce):
print 'start loop:',nloop,'at:',ctime()
sleep(nsce)
print 'loop:',nloop,'at:',ctime()
def main():
print 'start at:',ctime()
threads = []
nloops = range(len(loops))
for i in nloops:
t = threading.Thread(target=loop,args=(i,loops[i]))
threads.append(t)
print 'append'
for i in nloops:
threads[i].start()
print 'start'
for i in nloops:
threads[i].join()
print 'join'
print 'all done at:',ctime()
if __name__ == '__main__':
main()
上面代码中,t = threading.Thread(target=loop,args=(i,loops[i]))是创建了一个线程执行loop函数。args里面是loop函数的有关参数的赋值。
- call classes