#_ *_coding:utf-8_*_import threadingfrom time import sleep,ctime# number of seconds loops = [4,2]# This function simulates a function that is actually used to work Def loop (nloop,nsec): print "function%s start time:%s wait seconds :%s \n " % (Nloop,ctime (), nsec) sleep (nsec) #等待时间def main (): print "Main thread starts at %s start ...:" % ctime () threads = [] #这个列表用来存放创建的线程 nloops = range (len (loops)) # Introduce the loops list in the global variable, the generated local variable nloops as the index #顾nloops存储的是 [0,1] for I in nloops: t = threading. Thread (target=loop,args= (i,loops[i)) #创建线程 threads.append (t) #创建到线程累加存放到列表threads中 for i in nloops: &nbsP;threads[i].start () #所有线程创建完之后, convenient to store a list of threads and start thread for i in nloops together: threads[i].join () #程序挂起, until the end of the thread, no more administrative allocation locks, get locks, release locks, Check lock to status and so on, just call the join () function, print "All functions Complete:", ctime () if __name__ == ' __main__ ': main ()
Run results
/usr/bin/python2.7/home/toby/pycharmprojects/soms/test2.py
The main thread starts at Wed Mar 1 19:59:53 2017 ...:
Function 0 start time: Wed Mar 1 19:59:53 2017 wait seconds: 4
Function 1 start time: Wed Mar 1 19:59:53 2017 wait seconds: 2
All functions completed: Wed Mar 1 19:59:57 2017
This article is from the "Operation and maintenance of AC Q Group: 223843163" blog, please be sure to keep this source http://freshair.blog.51cto.com/8272891/1902532
Python's multi-threading threading Module