python程序:
#!/usr/bin/python
import threading
from time import ctime, sleep
loops = [2,4,3]
def loop(loop_num,sleep_time):
print 'start loop',loop_num,'at:',ctime()
sleep(sleep_time)
print 'done loop',loop_num,'at',ctime()
def sum_num():
a = 2
b =3
print a+b
def main():
print 'start time',ctime()
threads = []
lens = range(len(loops))
for i in lens:
if i <= len(loops)-2:
t = threading.Thread(target=loop,args=(i, loops[i]))
threads.append(t)
else:
t = threading.Thread(target=sum_num,args=())
threads.append(t)
for i in lens:
threads[i].start()
for i in lens:
threads[i].join()
print 'done all at',ctime()
if __name__ == '__main__':
main()
threading和thread模块的区别(个人理解):
threading不用具体到加锁,释放锁,join方法等价于对锁的管理。