Transferred from: http://www.cnblogs.com/fnng/p/3691053.html
Before talking about a multi-threaded blog, I feel the meaning of the words, in fact, multithreading is very interesting. Because we are in the process of using the computer in many processes and multi-threading. We can continue with the previous example. Please read my previous blog first.
The creation of threads from the above example is rather cumbersome, and each thread created needs to create a TX (T1, T2 、... ), if you create a thread that is extremely inconvenient. The following examples continue to improve:
player.py
#coding =utf-8from time Import sleep, CTime import threadingdef Muisc (func): For I in range (2): print ' Start playin G:%s! %s '% (Func,ctime ()) Sleep (2) def move (func): For I in range (2): print ' Start playing:%s!%s '% (Func,ctime ()) Sleep (5) def player (name): r = Name.split ('. ') [1] if r = = ' mp3 ': muisc (name) else: if r = = ' mp4 ': Move (name) else: print ' error:the format is Not recognized! ' list = [' Love trading. mp3 ', ' Avatar. mp4 ']threads = []files = range (len list) #创建线程for I in files: t = Threading. Thread (target=player,args= (List[i],)) threads.append (t) if __name__ = = ' __main__ ': #启动线程 for i in Files: Threads[i].start () for I in Files:threads[i].join () #主线程 print ' end:%s '%ctime ()
Interestingly, we also created a player () function, which is used to determine the type of playback file. If it is in MP3 format, we will call the music () function, if it is the MP4 format we call the Move () function. Which two formats are not so only to tell the user that you have provided a file I can not play.
Then we create a list of file lists, and note that the file is prefixed with a suffix name. We then use Len (list) to calculate how many files the list has, which is to help us determine the number of loops.
We then add the file in the list to the thread array threads[] in a for loop. Then start the threads[] thread group, and the last print end time.
Split () splits a string into two parts and then takes part of it.
>>> x = ' testing.py ' >>> s = x.split ('. ') [1]>>> if s== ' py ': print S
Py
Operation Result:
Start Playing: Love business. mp3! Mon APR 12:48:40 2014Start Playing: Avatar. mp4! Mon APR 12:48:40 2014Start Playing: Love business. mp3! Mon APR 12:48:42 2014Start Playing: Avatar. mp4! Mon Apr 12:48:45 2014end:mon Apr 21 12:48:50 2014
Now add a file to the list array, and the program will automatically create a thread for it when it runs.
Continue to improve the example:
Through the program above, we find that the player () is used to determine the file extension, then Call Music () and move (), in fact, music () and move () The full work is the same, why we do not do a super player, no matter what the file can be played. After the makeover, my super player was born.
super_player.py
#coding =utf-8from time Import sleep, CTime import threadingdef super_player (file,time): For I in range (2): print ' Start Playing:%s! %s '% (File,ctime ()) Sleep (time) #播放的文件与播放时长list = {' Love trading. mp3 ': 3, ' Avatar. mp4 ': 5, ' Me and you. mp3 ': 4}threads = []files = Range ( Len (list)) #创建线程for file,time in List.items (): t = Threading. Thread (target=super_player,args= (file,time)) threads.append (t) if __name__ = = ' __main__ ': #启动线程 for i in Files: Threads[i].start () for I in Files: threads[i].join () #主线程 print ' end:%s '%ctime ()
The dictionary list is created first to define the file to be played in time (seconds), and the dictionary's items () method is used to iterate through the files and hours, and the two values are taken to create the thread.
The Super_player () function is then created to receive file and time to determine the length of the file to be played.
Finally, the thread starts running. Operation Result:
Start Playing: Love business. mp3! Fri APR 09:45:09 2014Start Playing: Me and you. mp3! Fri APR 09:45:09 2014Start Playing: Avatar. mp4! Fri APR 09:45:09 2014Start Playing: Love trading. mp3! Fri APR 09:45:12 2014Start Playing: Me and you. mp3! Fri APR 09:45:13 2014Start Playing: Avatar. mp4! Fri Apr 09:45:14 2014end:fri Apr 25 09:45:19 2014
To create your own multithreaded class
#coding =utf-8import threading from time import Sleep, CTime class MyThread (threading. Thread): def __init__ (self,func,args,name= "): Threading. Thread.__init__ (self) self.name=name self.func=func Self.args=args def run (self): apply ( Self.func,self.args) def super_play (file,time): For I in range (2): print ' Start playing:%s!%s '% (File,ctime ()) Sleep (time) List = {' Love trading. mp3 ': 3, ' Avatar. mp4 ': 5} #创建线程threads = []files = range (len (list)) for k,v in List.items (): t = MyThread (Super_play, (k,v), super_play.__name__) threads.append (t) if __name__ = = ' __main__ ': #启动线程 for i in Files: Threads[i].start () for I in Files: threads[i].join () #主线程 print ' end:%s '%ctime ()
MyThread (Threading. Thread)
Creates a Mythread class for inheriting threading. Thread class.
__init__ ()
Initializes parameters such as Func, args, name, and so on, using the class's initialization method.
Apply ()
The Apply (func [, args [, Kwargs]]) function is used to indirectly invoke a function when a function parameter already exists in a tuple or dictionary. Args is a tuple that contains the arguments passed by position that will be supplied to the function. If args is omitted, no arguments are passed, and Kwargs is a dictionary containing the keyword arguments.
Apply () Usage:
#不带参数的方法 >>> def Say (): print ' say in ' >>> apply (say) say in# function only with tuple parameters >>> def say (A, B): Print a,b>>> Apply (say, (' Hello ', ' Zerg ')) Hello worm # function with keyword parameter >>> def say (a=1,b=2): Print A, b >>> def haha (**kw): apply (say, (), kw) >>> haha (a= ' a ', b= ' B ') a B
MyThread (Super_play, (k,v), super_play.__name__)
Because the Mythread class inherits the Threading.thread class, we can use the Mythread class to create threads.
Operation Result:
Start Playing: Love business. mp3! Fri APR 10:36:19 2014Start Playing: Avatar. mp4! Fri APR 10:36:19 2014Start Playing: Love trading. mp3! Fri APR 10:36:22 2014Start Playing: Avatar. mp4! Fri Apr 10:36:24 2014all End:fri Apr 25 10:36:29 2014
Python multithreading is so Simple (cont.)