Python Multithreading (i)

Source: Internet
Author: User

---restore content starts---

First, let's look at a single thread example:

 fromTime Import ctime,sleepdef Music (): forIinchRange2): Print ("I was listening to music.%s"%CTime ()) Sleep (1) def move (): forIinchRange2): Print ("I was at the movies!%s"%CTime ()) Sleep (5)if__name__ = ='__main__': Music () Move () print ("All over %s"%ctime ())

First listen to a piece of music, feel the sound, with a for loop to control the music played two times, each music playback takes 1 seconds, sleep () to control the duration of music playback,

I heard that a movie looks good, we go to see, every movie takes 5 seconds, the movie is in too good-looking, we have for loop 2 run results as follows:

I'm listening to music. Sun May -  A: the: the 2018I'm listening to music. Sun May -  A: the: - 2018you're watching a vibrato .! Sun May -  A: the: Wu 2018you're watching a vibrato .! Sun May -  A: the: - 2018All + Sun May -  A: -:Geneva 2018[Finishedinch  A.2s]

Through the top we see there are two ways to think we can customize what song to listen to, what kind of short video

The above code is then modified:

From time import Ctime,sleep

def music (song):
For I in range (2):
Print ("I'm listening to%s music. %s "% (Song,ctime ()))
Sleep (1)

def move (TV):
For I in range (2):
Print ("You are watching the vibrato%s short video! %s "% (Tv,ctime ()))
Sleep (5)

if __name__ = = ' __main__ ':
Music (' Chine ')
Move (' Eat chicken ')
Print ("All over%s"%ctime ())

See, we've added a parameter to run the result:

I'm listening to Chine music. Sun May -  A: +: - 2018I'm listening to Chine music. Sun May -  A: +: - 2018you're watching the vibrato, eating chicken, short videos .! Sun May -  A: +: - 2018you're watching the vibrato, eating chicken, short videos .! Sun May -  A: +: to 2018All + Sun May -  A: +: $ 2018[Finishedinch  A.2s]

Multithreading: It embodies the use of single-threaded, then we have to see what is more powerful multi-threaded function

 fromTime import CTime, Sleepimport threadingdef Music (song): forIinchRange2): Print ("I was listening to%s.%s"%(song, CTime ())) Sleep (1) def move (Mymove): forIinchRange2): Print ("I was at the %s!%s"%(Mymove, CTime ())) Sleep (5) Threads=[]th1= Threading. Thread (Target=music, args= ('go alone.',)) Threads.append (Th1) Th2= Threading. Thread (Target=move, args= ('Avengers Alliance',)) Threads.append (Th2)if__name__ = ='__main__':     forTinchThreads:t.setdaemon (True) # Setdaemon (true) declares a thread as a # daemon, which must be set before the start () method call, if # is not set to a daemon thread will be Infinite hangs. After the child thread is started, the # parent thread also continues execution when the parent thread finishes executing the last statement T.start () T.join () #程序加了个join () method, which is used to wait for thread # to terminate.    Join () is the role of the parent thread of this line # thread that is blocked until the child thread finishes running. Print ("All over %s"% CTime ())

First of all, you must import the Threading module: import threading

Threads = []th1 = Threading. Thread (Target=music, args= (' One person walking ',)) Threads.append (Th1) 

Creates a threads array, creates thread Th1, and uses 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 Th2 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, the array is traversed by a for loop. (the array is loaded with T1 and T2 two threads)

Setdaemon ()

Setdaemon (True) declares a thread as a daemon thread and must be set before the start () method call, if not set to the daemon, is 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.

Operation Result:

I was listening to a man walking. Sun May -  A: -: - 2018I was at the Avengers Alliance! Sun May -  A: -: - 2018I was listening to a man walking. Sun May -  A: -: the 2018I was at the Avengers Alliance! Sun May -  A: -: - 2018All + Sun May -  A: -: + 2018[Finishedinch Ten.3s]

Here we find that if I had a lot of threads, wouldn't it be that I had to create a th~ for each thread

#!user/bin/env python# Coding=utf-8 fromTime import CTime, Sleepimport threadingdef Music (song): forIinchRange2): Print ("I was listening to%s.%s"%(song, CTime ())) Sleep (1) def move (Mymove): forIinchRange2): Print ("I was at the %s!%s"%(Mymove, CTime ())) Sleep (5) def new_threading (name): New_thread= Name.split ('.')[1]    ifNew_thread = ='mp3': Music (name)Else:        ifNew_thread = ='mp4': Move (name)Else: Print ('error:the format is not recognized!') List= ['Chine. mp3','Avengers Alliance. MP4']threads=[]file_count=Range (len list) # Create thread forIinchFile_count:t= Threading. Thread (target=new_threading, args=(List[i],)) Threads.append (t) # Start threadif__name__ = ='__main__':     forTinchFile_count:threads[t].start () forTinchFile_count:threads[t].join () print ("All over %s"% CTime ())

We have added a way to add threads, and the program automatically creates a thread for the list as soon as it is added to it.

I was listening to Chine. mp3. Sun May -  A: +:Ten 2018I was at the Avengers Alliance. MP4! Sun May -  A: +:Ten 2018I was listening to Chine. mp3. Sun May -  A: +: One 2018I was at the Avengers Alliance. MP4! Sun May -  A: +: the 2018All + Sun May -  A: +: - 2018[Finishedinch Ten.2s]

is not implemented, we continue to optimize, found in new--threading have a judge file extension, and then call Music and move ()

So why not use a method (i.e. a software) to play music and movies at the same time?

#!user/bin/env python# Coding=utf-8 fromTime import CTime, Sleepimport threadingdef super_player (file_type,time): forIinchRange2): Print ("playing%s.%s"%(File_type, CTime ())) Sleep (time) List={'Chine. mp3':2,'Avengers Alliance 3.mp4':2,'the name of the people. WAV':4}threads=[]file_count=Range (len list) # Create thread forFile_type,timeinchList.items (): t= Threading. Thread (Target=super_player, args=(File_type,time)) Threads.append (t) # Boot threadif__name__ = ='__main__':     forTinchfile_count: # [T].setdaemon (True) # Setdaemon (true) declares a thread as # daemon, must be set before the start () method call, if # is not set to guard The thread guard will be suspended indefinitely. After the child thread is started, the # parent thread also continues to execute when the parent thread finishes executing the last statement Threads[t].start () forTinchFile_count:threads[t].join () # T.join () #只对上面的程序加了个join () method, used to wait for thread # to terminate.    Join () is the role of the parent thread of this line # thread that is blocked until the child thread finishes running. Print ("All over %s"% CTime ())

Here we change the list to a dictionary, define the file and duration of the play, and use the dictionary's items () method to iterate through file and time, and take these two values to create the thread.

Create the Super_player () function to receive file and time, which determines the length of files to play. The results of the operation are as follows:

Playing Chine. mp3. Sun May -  A: the: - 2018playing the Avengers league 3.mp4. Sun May -  A: the: - 2018is playing the name of the people. wav. Sun May -  A: the: - 2018playing Chine. mp3. Sun May -  A: the: + 2018playing the Avengers league 3.mp4. Sun May -  A: the: + 2018is playing the name of the people. wav. Sun May -  A: the: the 2018All + Sun May -  A: the: - 2018[Finishedinch 8.2s]

Python Multithreading (i)

Related Article

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.