Python multithreading is so simple

Source: Internet
Author: User

Multithreading and multi-process are self-built google's understanding of python multithreading. It took me a long time to search most articles that are not easy to understand. So here we try to use a simple example to give you a preliminary understanding of multithreading. Single thread in the MS-DOS era many years ago, the operating system to solve the problem is a single task, I want to listen to music and watch the movie two things, then be sure to sort out the order first. (Okay! In the DOS era, we don't need to worry about the applications of listening to music and watching movies. Pai_^) copy the code from time import ctime, sleep def music (): for I in range (2): print "I was listening to music. % s "% ctime () sleep (1) def move (): for I in range (2): print" I was at the movies! % S "% ctime () sleep (5) if _ name _ = '_ main _': music () move () print "all over % s" % ctime () copy the code. We listened to a piece of music and used the for loop to control the playing of the Music twice. It takes one second to play each music, sleep () to control the duration of music playback. Then we watched another movie. It took five seconds for every movie to be watched. Because it was so nice, I also watched it twice through the for loop. After the whole leisure and entertainment activity, I checked the current time and it was almost time to go to bed. Running result: copy the code >=============================== RESTART ======== ========================================>> I was listening to music. thu Apr 17 10:47:08 2014I was listening to music. thu Apr 17 10:47:09 2014I was at the movies! Thu Apr 17 10:47:10 2014I was at the movies! Thu Apr 17 10:47:15 2014all over Thu Apr 17 10:47:20 2014 actually, music () and move () should be considered as music and video players, it is up to us to decide what songs and videos to play. So the above Code is transformed: Copy Code # coding = utf-8import threadingfrom time import ctime, sleep def music (func): for I in range (2 ): print "I was listening to % s. % s "% (func, ctime () sleep (1) def move (func): for I in range (2): print" I was at the % s! % S "% (func, ctime () sleep (5) if _ name _ = '_ main _': music (u'love trading ') move (u 'avant') print "all over % s" % ctime () Copying code transmits parameters to music () and move. Experience Chinese classic songs and major European and American cultures. Running result: copy the code >>================================ RESTART ============== ====================================>>> I was listening to love trading. thu Apr 17 11:48:59 2014I was listening to love trading. thu Apr 17 11:49:00 2014I was at the Avatar! Thu Apr 17 11:49:01 2014I was at the Avatar! Thu Apr 17 11:49:06 2014all over Thu Apr 17 11:49:11 2014 the multi-thread technology for code replication is developing, the times are improving, and our CPU is getting faster and faster, CPU complaints, P has taken some time for me to do big things. In fact, it is okay for me to do multiple jobs at the same time. Therefore, the operating system has entered the multi-task era. It's not our dream to listen to music and eat hot pot. Python provides two modules to implement multi-threaded thread and threading. thread has some shortcomings and can be compensated in threading. In order not to waste you and time, we can directly learn threading. Continue to transform the above example, introduce threadring to play music and video simultaneously: copy the Code # coding = utf-8import threadingfrom time import ctime, sleep def music (func ): for I in range (2): print "I was listening to % s. % s "% (func, ctime () sleep (1) def move (func): for I in range (2): print" I was at the % s! % S "% (func, ctime () sleep (5) threads = [] t1 = threading. thread (target = music, args = (u 'Sale of love',) threads. append (t1) t2 = threading. thread (target = move, args = (u 'avant',) threads. append (t2) if _ name _ = '_ main _': for t in threads: t. setDaemon (True) t. start () print "all over % s" % ctime () Copying code import threading first imports the threading module, which is the premise of multithreading. Threads = [] t1 = threading. thread (target = music, args = (u 'Sale of love',) threads. append (t1) creates a threads array, creates thread t1, and uses threading. thread () method. In this method, the music method target = music is called, and The args method is used to transmit parameters to music. Install the created thread t1 in the threads array. Create thread t2 in the same way, and load t2 to the threads array. For t in threads: t. setDaemon (True) t. start () Finally, the array is traversed through the for loop. SetDaemon () setDaemon (True) declares the thread as a daemon. It must be set before the start () method is called. If it is not set as a daemon, it will be suspended infinitely. After the sub-thread starts, the parent thread continues to run. After the parent thread finishes executing the last statement print "all over % s" % ctime (), it does not wait for the sub-thread, the sub-thread is also terminated. Start () starts thread activity. Running result: >>> ======================================= RESTART ==================== ============================>>> I was listening to love trading. thu Apr 17 12:51:45 2014 I was at the Avatar! Thu Apr 17 12:51:45 2014 all over Thu Apr 17 12:51:45 2014 from the execution results, the sub-thread (muisc, move) and the main thread (print "all over % s" % ctime ()) it is started at the same time, but the sub-thread is terminated because the execution of the main thread ends. Continue to adjust the program: copy the code... if _ name _ = '_ main _': for t in threads: t. setDaemon (True) t. start () t. join () print "all over % s" % ctime () copy the code. We only add a join () method to the above program to wait for the thread to terminate. The function of join () is that the parent thread of this subthread will be blocked until the subthread completes running. Note: The position of the join () method is outside the for loop. That is to say, the main process must be executed only after the two processes in the for loop are completed. Running result: copy the code >>============================== RESTART ========== ======================================>> I was listening to love trading. thu Apr 17 13:04:11 2014 I was at the Avatar! Thu Apr 17 13:04:11 2014 I was listening to love trading. Thu Apr 17 13:04:12 2014I was at the Avatar! Thu Apr 17 13:04:16 2014all over Thu Apr 17 13:04:21 2014 copy the code. The execution result shows that music and move are started at the same time. The start time is 4 minutes 11 seconds until the main process called is 4 minutes 22 seconds and the total time is 10 seconds. It is reduced from a single thread by 2 seconds. We can adjust the sleep () Time 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 result: copy the code >>================================== RESTART ================== ================================>>> I was listening to love trading. thu Apr 17 13:11:27 2014I was at the Avatar! Thu Apr 17 13:11:27 2014 I was listening to love trading. Thu Apr 17 13:11:31 2014I was at the Avatar! Thu Apr 17 13:11:32 2014all over Thu Apr 17 13:11:37 2014 copy the code

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.