Python thread concurrency and sequential run sample _python

Source: Internet
Author: User
Copy Code code as follows:

#-*-Coding:utf-8-*-
Import threading
Import time
def fun (name, ls_name, Front_thread = None):
'''''
Thread Start function
Using Front_thread to run the thread in order
'''
Time.clock ()
Time.sleep (2)
# If Front_thread exists, the current thread will not run until the Front_thread run completes
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 ()
# Start 1000 Threads each
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)

# Waiting for all threads to end
For T in Ls_thread:
T.join ()

print ' Ls_result_name: ', ls_result_name
print "main thread:%s"% Time.clock ()

The results of the operation are:
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]
Main thread:2.003211302
Thread for more detailed use can refer to:
Http://docs.python.org/library/threading.html
A more detailed description of the Time.clock module can be referred to:
Http://blog.csdn.net/kiki113/archive/2009/03/28/4033017.aspx

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.