Example of concurrent and sequential running of Python thread

Source: Internet
Author: User

CopyCode The Code is as follows: #-*-coding: UTF-8 -*-
Import threading
Import time
Def fun (name, ls_name, front_thread = none ):
'''''
Thread start Function
Use front_thread to run threads in an orderly manner
'''
Time. Clock ()
Time. Sleep (2)
# If front_thread exists, the current thread will be run only after the front_thread is completed
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 Up 1000 threads one by one
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 until all threads end
For T in ls_thread:
T. Join ()

Print 'ls _ result_name: ', ls_result_name
Print "main thread: % s" % time. Clock ()

running result:
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
more detailed use of threads can be referred to:
http://docs.python.org/library/threading.html
time. for more information about the clock module, see
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.