Python threads run the example concurrently and sequentially
- 2020-04-02 09:23:00
- OfStack
#-*- coding:utf-8 -*-
import threading
import time
def fun(name, ls_name, front_thread = None):
'''''
Thread startup function
through front_thread To use threads to run in order
'''
time.clock()
time.sleep(2)
# if front_thread Where there is, there is front_thread When the run is complete, run the current thread
if front_thread != None:
front_thread.join()
ls_name.append(name)
print "thread %s : %s"% (name, time.clock())
if __name__ == '__main__':
ls_result_name = []
ls_thread = []
time.clock()
# One by one, to start 1000 A thread
for i in range(0,10):
if len(ls_thread) == 0:
t = threading.Thread(target=fun, args=(i,ls_result_name,None))
else:
t = threading.Thread(target=fun, args=(i,ls_result_name,ls_thread[-1]))
t.start()
ls_thread.append(t)
# Wait for all threads to finish
for t in ls_thread:
t.join()
print 'ls_result_name:', ls_result_name
print "main thread:%s" % time.clock()
The running result is:
Thread 0, 1.99962006344
Thread 1:2.00000866032
Thread 2:2.00059113658
Thread 3:2.00080345407
Thread 4:2.00100068584
Thread 5:2.00119456523
Thread 6:2.00138593033
Thread 7:2.00166753037
Thread 8:2.00211758757
Thread 9:2.0024776892
Ls_result_name: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
The main thread: 2.003211302
More detailed use of threads can be referred to:
http://docs.python.org/library/threading.html
For a more detailed introduction of the time.clock module, please refer to:
http://blog.csdn.net/kiki113/archive/2009/03/28/4033017.aspx