Python Multithreading is so simple

Source: Internet
Author: User


Source: Linux Community Stitchsun multithreading and multi-process is what Google brain for Python multi-threading understanding, I spent a long time, most of the search articles are not easy to understand. So, here is trying to use a simple example, so you have a preliminary understanding of multithreading. Single-threaded in MS-dos era years ago, operating system processing problems are single-tasking, I want to do listening to music and watching movies two things, then must first order. (All right!) We don't struggle with the use of listening to music and seeing shadows in the age of DOS. ^_^)
1  fromTime Import Ctime,sleep2 3 def Music ():4      forIinchRange2):5Print"I was listening to music.%s"%CTime ()6Sleep1)7 8 def move ():9      forIinchRange2):TenPrint"I was at the movies!%s"%CTime () OneSleep5) A  - if__name__ = ='__main__': - Music () the Move () -Print"All over %s"%ctime ()

We listened to a piece of music and controlled the music playback two times with a For loop, which took 1 seconds and sleep () to control how long the music was playing. Then we watched a movie, and each movie took 5 seconds, because it was so nice, so I looked through the for loop two times. At the end of the entire leisure activity, I passed
Print "All over%s"%ctime () look at the current time, it's almost bedtime. Running result: >>=========================== RESTART ================================
>>>
I was listening to music. Thu APR 17 10:47:08 2014
I was listening to music. Thu APR 17 10:47:09 2014
I was at the movies! Thu APR 17 10:47:10 2014
I was at the movies! Thu APR 17 10:47:15 2014
All over Thu APR 17 10:47:20 2014 In fact, music () and move () should be seen more as musical and video players, as to what songs and videos to play should be determined by our use. So, we have modified the above code:
1#coding =utf-82 Import Threading3  fromTime Import Ctime,sleep4 5 def Music (func):6      forIinchRange2):7Print"I was listening to%s.%s"%(Func,ctime ())8Sleep1)9 Ten def Move (func): One      forIinchRange2): APrint"I was at the %s!%s"%(Func,ctime ()) -Sleep5) -  the if__name__ = ='__main__': -Music (U'Love Business') -Move (U' Avatar') -  +Print"All over %s"%ctime ()

The music () and move () are passed to the parameter. Experience Chinese classic songs and large-and-Western culture. Running results:>>> ======================== RESTART ================================
>>>
I was listening to love business. Thu APR 17 11:48:59 2014
I was listening to love business. Thu APR 17 11:49:00 2014
I was at the avatar! Thu APR 17 11:49:01 2014
I was at the avatar! Thu APR 17 11:49:06 2014
All over Thu APR 17 11:49:11 2014 Multi-Threading technology in the development, the times in progress, our CPU is also getting faster, CPU complaining, p big point of the matter accounted for me a certain time, in fact, I do a lot of work at the same time no problem, so the operating system into the multi-tasking era.  We listen to the music eating hot pot is not the dream. Python provides two modules to implement multithreading thread and threading, thread has some shortcomings, in threading get made up, in order not to waste you and time, so we directly learn threading can be. Continue to transform the example above, introducing threadring to play music and video simultaneously:
1#coding =utf-82 Import Threading3  fromTime Import Ctime,sleep4 5 def Music (func):6      forIinchRange2):7Print"I was listening to%s.%s"%(Func,ctime ())8Sleep1)9 Ten def Move (func): One      forIinchRange2): APrint"I was at the %s!%s"%(Func,ctime ()) -Sleep5) -  theThreads = [] -T1 = Threading. Thread (target=music,args= (U'Love Business',)) - threads.append (t1) -T2 = Threading. Thread (target=move,args= (U' Avatar',)) + threads.append (T2) -  + if__name__ = ='__main__': A      forTinchThreads: at T.setdaemon (True) - T.start () -  -Print"All over %s"%ctime ()

Import threading First imports the threading module, which is the premise of using multithreading. Threads = []T1 = Threading. Thread (target=music,args= (U ' Love Trade ',)) threads.append (T1) created the threads array, created the thread T1, and used threading. The Thread () method, in which the music method is called by the Target=music,args method to pass a parameter to the music.  Load the created thread T1 into the threads array. The thread T2 is then created in the same way, and the T2 is also loaded into the threads array. For T in Threads:t.setdaemon (True) T.start () finally iterates through the array with a for loop. (the array is loaded with T1 and T2 two threads) Setdaemon () Setdaemon (True) declares the thread as a daemon thread and must be set before the start () method call, if not set to the daemon, will be indefinitely suspended. After the child thread is started, the parent thread continues to execute, and when the parent thread finishes executing the last statement print "All over%s"%ctime (), it exits without waiting for the child thread, and the child threads end together. Start () starts the thread activity. Running results:>>> ========================= RESTART ================================
>>>
I was listening to love business. Thu APR 12:51:45 I was at the avatar! Thu Apr 12:51:45 all over Thu APR 17 12:51:45 2014 from the execution result, the child thread (Muisc, move) and the main thread (print "All over%s"%ctime ()) are Starts at the same time, but causes the child thread to terminate because the main thread finishes executing. Continue to adjust the program: ...
if __name__ = = ' __main__ ':
For T in Threads:
T.setdaemon (True)
T.start ()

T.join () print "All over%s"%ctime () we only added a join () method to the above program to wait for the thread to terminate.  The role of Join () is that the parent thread of this child thread will remain blocked until the child thread finishes running. Note: The position of the join () method is outside the for loop, which means that you must wait for the two processes in the For loop to finish before executing the main process. Running results:>>> ========================= RESTART ================================
>>>
I was listening to love business. Thu APR 13:04:11 I was at the avatar! Thu APR 13:04:11 2014I was listening to love business. Thu APR 17 13:04:12 2014
I was at the avatar! Thu APR 17 13:04:16 2014
All over Thu APR 17 13:04:21 2014 from the execution results you can see that music and move are started at the same time. The start time is 4 minutes and 11 seconds, until the main process is called 4 minutes and 22 seconds, which takes a total of 10 seconds. With a reduction of 2 seconds from a single thread, we can adjust the time of sleep () of music to 4 seconds. ...
def music (func):
For I in range (2):
Print "I was listening to%s.%s"% (Func,ctime ())
Sleep (4)
... Execution results:>>> ====================== RESTART ================================
>>>
I was listening to love business. Thu APR 13:11:27 2014I was at the avatar! Thu APR 13:11:27 2014I was listening to love business. Thu APR 17 13:11:31 2014
I was at the avatar! Thu APR 17 13:11:32 2014
All over Thu APR 17 13:11:37 2014 child threads start 11 minutes and 27 seconds, and the main thread runs for 11 minutes and 37 seconds. Although the music each song from 1 seconds extended to 4, but the way to run a multi-thread script, the total time has not changed.

Python multithreading is so simple

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.