Understanding Python Multithreading (Python multithreaded Concise tutorial) _python

Source: Internet
Author: User
Tags current time sleep thread class

It took me a long time to understand Python multithreading, and most of the articles I searched were less than straightforward. So, here, try to use a simple example, let you have a preliminary understanding of multithreading.

Single Thread

In the MS-DOS era a few years ago, operating system processing problems are single task, I want to listen to music and watch movies two things, then must first arrange order.

(All right!) We don't struggle with the use of listening to music and seeing in the DOS era. ^_^)

Copy Code code as follows:

From time import Ctime,sleep

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

def move ():
For I in range (2):
Print "I is at the movies! %s '%ctime ()
Sleep (5)

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

We first listened to a piece of music, through a for loop to control the music played two times, each music playback needs 1 seconds, sleep () to control the length of the music playback. And then we watched a movie,

Every movie takes 5 seconds, because it looks so good, so I look at it two times through the for loop. At the end of the whole leisure and recreational activity, I passed

Copy Code code as follows:

Print "All over%s"%ctime ()

Looking at the current time, it's almost bedtime.

Run Result:

Copy Code code as follows:

>>=========================== 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 viewed as musical and video players, as well as what songs and videos to play should be decided by us when we use them. So, we've transformed the code above:

Copy Code code as follows:

#coding =utf-8
Import threading
From time import Ctime,sleep

def music (func):
For I in range (2):
Print "I is listening to%s.%s"% (Func,ctime ())
Sleep (1)

def move (func):
For I in range (2):
Print "I is at the%s! %s '% (Func,ctime ())
Sleep (5)

if __name__ = = ' __main__ ':
Music (U ' Love Business ')
Move (U ' Avatar ')

Print "All over%s"%ctime ()

The music () and move () are treated with parameters. Experience the Chinese classic songs and large and Western culture.

Run Result:

Copy Code code as follows:

>>> ======================== 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 am at the Avatar! Thu APR 17 11:49:01 2014
I am at the Avatar! Thu APR 17 11:49:06 2014
All over Thu APR 17 11:49:11 2014

Multithreading

Technology in the development of the Times in progress, our CPU is also getting faster, CPU complaints, p big things take up my time, in fact, I do a lot of work at the same time no problem; So, Operation department

The unification has entered the multitasking time. We listen to music eating hotpot is not a dream.

Python provides two modules to implement multithreaded thread and threading, thread has some drawbacks in threading got made up, in order not to waste you and time, so we're straight

Then you can learn threading.

Continue to transform the example above to introduce threadring to play music and video at the same time:

Copy Code code as follows:

#coding =utf-8
Import threading
From time import ctime,sleep


def Music (func):
    for I in range (2):
        Print ' I am listening to%s '% (Func,ctime ())
        Sleep (1)

def move (func ):
    for I in range (2):
        Print I is at the%s! %s '% (Func,ctime ())
        Sleep (5)

Threads = []
T1 = Threading. Thread (target=music,args= (U ' Love Sale ',))
Threads.append (t1)
T2 = Threading. Thread (target=move,args= (U ' Avatar ',))
Threads.append (T2)

If __name__ = = ' __main__ ':
    For T in Threads:
        T.setdaemon (True)
         T.start ()

    print "All over%s"%ctime ()

Import threading

First, import the threading module, which is the premise of using multithreading.

Copy Code code as follows:

Threads = []
T1 = Threading. Thread (target=music,args= (U ' Love Business '))
Threads.append (T1)

created the threads array, created the thread T1, and used threading. Thread () method, in which the music method Target=music,args method is invoked to pass the music parameter. The creation

The built thread T1 into the threads array.

The thread T2 is then created in the same way, and the T2 is also mounted to the threads array.


Copy Code code as follows:

For T in Threads:
T.setdaemon (True)
T.start ()

Finally, the array is traversed through a for loop. (Arrays are loaded with T1 and T2 two threads)

Setdaemon ()

Setdaemon (True) declares a thread as a daemon and must be set before the start () method is called, if it is not set to a daemon, it will be indefinitely suspended. When a child thread starts, the parent line

The thread also continues to execute, when the parent thread finishes executing the last statement print "All over%s"%ctime (), does not wait for the child thread, exits directly, and the child thread ends together.

Start ()

Start thread activity.
Run Result:

Copy Code code as follows:

>>> ========================= Restart ================================
>>>
I was listening to love business. Thu APR 12:51:45 2014 I was at the avatar! Thu Apr 12:51:45 2014 all over Thu APR 17 12:51:45 2014

From the execution result, the child threads (Muisc, move), and the main thread (print "All over%s"%ctime ()) are all started at the same time, but cause the child thread to terminate because the main thread finishes executing.

Continue to adjust the program:

Copy Code code as follows:

...
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. Join () is used to keep the parent thread of this child thread from blocking until the child thread finishes running.

Note: The join () method is positioned outside of the for loop, which means that you must wait for the two processes in the For loop to complete before executing the main process.

Run Result:

Copy Code code as follows:

>>> ========================= Restart ================================
>>>
I was listening to love business. Thu APR 13:04:11 2014 I was at the avatar! Thu APR 17 13:04:11 2014

I was listening to love business. Thu APR 17 13:04:12 2014
I am at the Avatar! Thu APR 17 13:04:16 2014
All over Thu APR 17 13:04:21 2014

As you can see from the execution results, music and move are started at the same time.

The start time is 4 minutes and 11 seconds until the calling main process is 4 minutes and 22 seconds, which takes a total of 10 seconds. With a 2-second reduction from single-threaded, we can adjust the time of music Sleep () to 4 seconds.

Copy Code code as follows:

...
def music (func):
For I in range (2):
Print "I is listening to%s.%s"% (Func,ctime ())
Sleep (4)
...

Execution results:

Copy Code code as follows:

>>> ====================== Restart ================================
>>>
I was listening to love business. Thu APR 13:11:27 2014I is at the avatar! Thu APR 17 13:11:27 2014

I was listening to love business. Thu APR 17 13:11:31 2014
I am at the Avatar! Thu APR 17 13:11:32 2014
All over Thu APR 17 13:11:37 2014

The child thread starts 11 minutes and 27 seconds, and the main thread runs 11 minutes and 37 seconds.

Although music per song was extended from 1 seconds to 4, the way to run the script in the path of multiple threads was unchanged for the total time.

This article gives you a quick understanding of the use of Python multithreading in more detail, and refer to other documents or materials for more detailed use.

==========================================================

Class Threading. Thread () Description:


Copy Code code as follows:

Class Threading. Thread (Group=none, Target=none, Name=none, args= (), kwargs={})

This constructor should always is called with keyword arguments. Arguments are:

Group should be None; Reserved for future extension when a threadgroup the class is implemented.

Target is the callable object of invoked by the run () method. Defaults to None, meaning what is called.

Name is the thread name. By default, a unique name is constructed to the form "Thread-n" where N is a small decimal number.

The args is the argument tuple for the target invocation. Defaults to ().

Kwargs is a dictionary of keyword arguments for the target invocation. Defaults to {}.

If the subclass overrides the constructor, it must make sure to invoke the base class constructor (Thread.__init__ ()) befo Re doing

Anything else to the thread.


Previously told a multithreaded blog, feeling that the meaning is still not exhausted, in fact, multithreading is very interesting. Because we are in the process of using the computer all the times in many processes and multithreading. We can go on to the previous example. Please see my last blog first.


From the example above, it is quite troublesome to create a thread, and each creation of a thread requires the creation of a TX (T1, T2 、... ), it is extremely inconvenient to create threads when they are created more often. The following are examples of continuing improvements:

player.py

Copy Code code as follows:

#coding =utf-8
From time to import sleep, CTime
Import threading

def muisc (func):
For I in range (2):
print ' Start Playing:%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 business. 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 have created a player () function that is used to determine the type of playback file. If it's in MP3 format, we'll call the music () function, and if it's the MP4 format we call the Move () function. Which of the two formats is not so that you can only tell the user that you have provided the file I can not play.

Then, we create a list of files for the list, and note that the suffix name is appended to the file. Then we use Len (list) to calculate how many files the list has, and this is to help us determine the number of loops.

Then we add the file in the list to the thread array threads[] through a for loop. Next starts the threads[] thread group, and finally prints the end time.

Split () splits a string into two parts and then takes a portion of it.


Copy Code code as follows:

>>> x = ' testing.py '
>>> s = X.split ('. ') [1]
>>> if s== ' py ':
Print S


Py

Run Result:

Copy Code code as follows:

Start Playing: Love business. mp3! Mon APR 21 12:48:40 2014
Start Playing: Avatar mp4!. Mon APR 21 12:48:40 2014
Start Playing: Love business. mp3! Mon APR 21 12:48:42 2014
Start Playing: Avatar mp4!. Mon APR 21 12:48:45 2014
End: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:

With the above program, we find that the player () is used to determine the file name extension and then Call Music () and move (), in fact, music () and move () are the same, and why don't we do a super player, no matter what files can play. After the makeover, my super player was born.

super_player.py

Copy Code code as follows:

#coding =utf-8
From time to import sleep, CTime
Import threading

def 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 ()

First, create a dictionary list that defines the length of time (in seconds) to be played, and the use of the dictionary's items () method to loop through file and moment to create a thread.

The Super_player () function is then created to receive file and time to determine how long the files are to be played.

Finally, the thread starts running. Run Result:

Copy Code code as follows:

Start Playing: Love business. mp3! Fri APR 25 09:45:09 2014
Start Playing: Me and you. mp3! Fri APR 25 09:45:09 2014
Start Playing: Avatar mp4!. Fri APR 25 09:45:09 2014
Start Playing: Love business. mp3! Fri APR 25 09:45:12 2014
Start Playing: Me and you. mp3! Fri APR 25 09:45:13 2014
Start Playing: Avatar mp4!. Fri APR 25 09:45:14 2014
END:FRI APR 25 09:45:19 2014

To create your own multithreaded class

Copy Code code as follows:

#coding =utf-8
Import threading
From time to 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)

Create a Mythread class for inheriting threading. The thread class.


__init__ ()

Initializes parameters such as Func, args, name, and so on, using the initialization method of the class.

Apply ()

Apply (func [, args [, Kwargs]]) functions are used to invoke functions indirectly when function arguments already exist in a tuple or dictionary. Args is a tuple that contains the arguments that are passed by location that will be supplied to the function. If args is omitted, no arguments are passed, Kwargs is a dictionary that contains the keyword parameters.

Apply () Usage:

Copy Code code as follows:

#不带参数的方法
>>> def say ():
print ' Say in '

>>> Apply (say)
Say in

#函数只带元组的参数
>>> def Say (a,b):
Print A,b

>>> apply (say, (' hello ', ' Bug '))
Hello Bug Master

#函数带关键字参数
>>> 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 the thread.

Run Result:

Copy Code code as follows:

Start Playing: Love business. mp3! Fri APR 25 10:36:19 2014
Start Playing: Avatar mp4!. Fri APR 25 10:36:19 2014
Start Playing: Love business. mp3! Fri APR 25 10:36:22 2014
Start Playing: Avatar mp4!. Fri APR 25 10:36:24 2014
All END:FRI APR 25 10:36:29 2014

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.