Home PC Games Linux Windows Database Network Programming Server Mobile  
           
  Home \ Programming \ The simple multi-threaded Python     - Oracle 11g RAC automatically play GI PSU patch (11.2.0.4.8) (Database)

- Through Oracle to help restore MySQL data problems (Database)

- Handle large data problems Bit-map method (Programming)

- Restrict console access to Linux servers to improve security (Linux)

- Installed FFmpeg 2.6.3 on Ubuntu / Debian / Fedora system (Linux)

- Grub2: Save Your bootloader (Linux)

- Dom4j change XML coding (Programming)

- VirtualBox - Linux system virtual machine shared folders (Linux)

- Fedora 20, Fedora 19, CentOS 6 and RHEL6 users how to install Wine 1.7.15 (Linux)

- MySQL 5.7.10 source code for the latest version of the installation process in detail (Database)

- MongoDB 3.0 New Features (Database)

- Install the Red Hat Container Development Kit on OSX (Server)

- PostgreSQL use pgpool achieve high availability (Database)

- Quick Install software RAID on Linux (Linux)

- 11 you Linux Terminal Command (Linux)

- RHEL 6.6 install GNOME desktop environment (Linux)

- Linux kernel IPv6 protocol closed manner (Linux)

- Redmine Installation (Linux)

- GAMIT learning materials finishing (Linux)

- How to use the Linux terminal Git commands (Linux)

 
         
  The simple multi-threaded Python
     
  Add Date : 2018-11-21      
         
         
         
  Multi-threading and multi-process what their own google Bunao

For Python multithreaded understanding, I took a long time, most of the articles are not enough search straightaway. So, here trying to use a simple example, let you have a multi-threaded preliminary understanding.

Threaded

In better years ago, the era of MS-DOS, the operating system deal with the problem is a single task, I want to listen to music and cinema are two things children, then we must first look at the order of discharge.

(Okay! We do not tangle in the DOS era whether there is music and video applications. ^ _ ^)

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

 We first heard a piece of music, to control music playback through the for loop twice, each music player takes 1 second, sleep () to control music playback duration. Then we watched a movie,

Every 5 seconds a movie, because good read, so I read it over twice by the for loop. At the end of the entire recreational activities, I passed
print "all over% s"% ctime ()

I looked at the current time, almost to bed.

The 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 as a music and video player, as to what you want to play songs and videos should be decided by our use. So, we made a transformation of the code above:

# Coding = utf-8
import threading
from 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 'Avatar')

    print "all over% s"% ctime ()

To music () and move () carried out mass participation process. Experience Chinese culture blockbuster songs and Europe.

The result:

>>> ======================== RESTART ====================== ==========
>>>
I was listening to love trading. Thu Apr 17 11:48:59 2014
I was listening to love trading. 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

Multithreading

In the development of science and technology, the era of progress, we are getting faster and faster CPU, CPU complain, P accounted for a big point thing I have time, I actually did not live at the same time doing more of the problem; thus, the operating system into the multitasking era. We listened to music and eating hot pot is not a dream.

python provides two modules to achieve multi-threaded thread and threading, thread has some disadvantages, in threading got to make up, and in order not to waste your time, so we will be able to directly learn threading.

Continue to transform the above example, the introduction of threadring to simultaneously play music and video:

# Coding = utf-8
import threading
from 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 'love trading'))
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 threading module, which is a prerequisite for the use of multi-threading.

threads = []

t1 = threading.Thread (target = music, args = (u 'love trading'))

threads.append (t1)

Create an array of threads to create a thread t1, using threading.Thread () method, call this method music method target = music, args parameter passing methods of music performed. To create a good thread t1 threads attached to the array.

Then in the same way to create a thread t2, and t2 are also attached to the threads of the array.

for t in threads:

t.setDaemon (True)

t.start ()

Finally, for loop through the array. (The array is loaded with two threads t1 and t2)

setDaemon ()

setDaemon (True) will declare a thread as a daemon thread, you must start before the method call set (), if you do not set a daemon thread program will be infinitely suspended. After the child thread starts, the parent thread can continue execution, when the parent thread executing the last statement print "all over% s"% ctime () later, no waiting for child thread directly quit, while the child thread also ends together.

start ()

Start thread activity.

The 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 results of the implementation, the sub-thread (muisc, move) and the main thread (print "all over% s"% ctime ()) at the same time to start, but since the end of the main thread executed, resulting in the child thread to terminate.

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 above program added a join () method, used to wait for the thread to terminate. join () function is, until the child thread finishes running, the parent of the child thread thread will be blocked.

NOTE: Position join () method is for outside the loop, that loop must wait for the end of the two processes, before going to execute the main process.

The result:

>>> ========================= 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 2014
I was at the Avatar! Thu Apr 17 13:04:16 2014
all over Thu Apr 17 13:04:21 2014

It can be seen from the results of the implementation, music and move simultaneously activated.

Start time of 4 minutes and 11 seconds, until you call the main process is 4 minutes and 22 seconds, the total time of 10 seconds. When single-threaded reduced from 2 seconds, we can put the music of sleep () the time was adjusted to 4 seconds.

...
def music (func):
    for i in range (2):
        print "I was listening to% s.% s"% (func, ctime ())
        sleep (4)
...

Results of the:

>>> ====================== 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 2014
I was at the Avatar! Thu Apr 17 13:11:32 2014
all over Thu Apr 17 13:11:37 2014

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

Although the music of each song extended from 1 second to 4, but through multi-pass lines run the script, did not change the total time.

In this paper, in the sense that allows you to quickly understand the use python multithreading, more detailed usage, please refer to other documents or information.

class threading.Thread () Description:

class threading.Thread (group = None, target = None, name = None, args = (), kwargs = {})

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

group should be None; reserved for future extension when a ThreadGroup class is implemented.

target is the callable object to be invoked by the run () method. Defaults to None, meaning nothing is called.

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

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 __ ()) before doing

anything else to the thread.

Speaking before a multithreaded a blog, talking about feeling something more to say, in fact, multithreading is very interesting. Because we have all the time in the multi-process and multi-threaded process using computers. We can then continue to talk about the previous example. Please see my previous blog.

python multithreading so simple

Found from the above example is quite troublesome to create a thread, each thread to create a need to create a tx (t1, t2, ...), if you create a multi-thread this time extremely inconvenient. Next, by way of example to continue to improve:

player.py

# Coding = utf-8
from time 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 trading .mp3', 'Avatar .mp4']

threads = []
files = range (len (list))

# Create a thread
for i in files:
    t = threading.Thread (target = player, args = (list [i],))
    threads.append (t)

if __name__ == '__main__':
    # Start a thread
    for i in files:
        threads [i] .start ()
for i in files:
threads [i] .join ()

    # Main thread
    print 'end:% s'% ctime ()

Interestingly we have created a player () function, which is used to determine the type of play the file. If the mp3 format, we will call the music () function, if it is mp4 format we call move () function. What if neither format so users can tell what you have provided me play this file.

Then, we created a list of list file, note the file name suffix. Then we use len (list) list list to calculate the number of files, which is to help us determine the number of cycles.

Then we passed a for loop to add to the list of files in an array of thread threads [] in. Then start threads [] thread group, the last print end time.

    split () can split a string into two parts, and then take part.

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

    
py

The result:

Start playing: love trading .mp3 Mon Apr 21 12:48:40 2014!
Start playing: Avatar .mp4 Mon Apr 21 12:48:40 2014!
Start playing: love trading .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 in an array, the program runs automatically creates a thread.

Continue to improve examples:

Through the above procedures, we found that player () is used to determine the file name extension, and then call the music () and move (), in fact, music () and move () complete work is the same, why we do not do a super player it is, no matter what the file can be played. After transformation, my super player was born.

super_player.py

# Coding = utf-8
from time import sleep, ctime
import threading

def super_player (file, time):
    for i in range (2):
        print 'Start playing:% s% s!'% (file, ctime ())
        sleep (time)

# Play files playback duration
list = { 'love trading .mp3': 3, 'Avatar .mp4': 5, 'Me and you .mp3': 4}

threads = []
files = range (len (list))

# Create a thread
for file, time in list.items ():
    t = threading.Thread (target = super_player, args = (file, time))
    threads.append (t)

if __name__ == '__main__':
    # Start a thread
    for i in files:
        threads [i] .start ()
for i in files:
threads [i] .join ()

    # Main thread
    print 'end:% s'% ctime ()

First, create a dictionary list, used to define the file to play in time length (seconds), take the file and time through the dictionary items () method to loop, whichever of these two values is used to create threads.

Then create super_player () function for receiving a file and time, is used to determine the file to play long in time.

Finally, the thread starts running. The result:

Start playing: love trading .mp3 Fri Apr 25 09:45:09 2014!
Start playing: you and me .mp3 Fri Apr 25 09:45:09 2014!
Start playing: Avatar .mp4 Fri Apr 25 09:45:09 2014!
Start playing: love trading .mp3 Fri Apr 25 09:45:12 2014!
Start playing: you and me .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

Create your own multithreaded class

# Coding = utf-8
import 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}

# Create a thread
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__':
    # Start a thread
    for i in files:
        threads [i] .start ()
for i in files:
threads [i] .join ()

    # Main thread
    print 'end:% s'% ctime ()

MyThread (threading.Thread)

Create MyThread class to inherit threading.Thread class.

__init __ ()

Class initialization method of func, args, name and other parameters are initialized.

apply ()

apply (func [, args [, kwargs]]) when the function is used when the function parameter already exists in a tuple or a dictionary, indirectly calling function. args is to be supplied to a function that contains tuples parameter passed by location. If you omit the args, any parameters will not be passed, kwargs is a dictionary containing the keyword parameter.

apply () usage:

# Method without parameters
>>> Def say ():
    print 'say in'

>>> Apply (say)
say in

# Function only with the argument tuple
>>> Def say (a, b):
    print a, b

>>> Apply (say, ( 'hello', 'Mushishi'))
hello Mushishi

# Function with keyword arguments
>>> 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__)

Since MyThread class inherits threading.Thread class, so we can use MyThread class to create a thread.

The result:

Start playing: love trading .mp3 Fri Apr 25 10:36:19 2014!
Start playing: Avatar .mp4 Fri Apr 25 10:36:19 2014!
Start playing: love trading .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
     
         
         
         
  More:      
 
- Spark parquet merge metadata problem (Server)
- SA weak password security system of the security risks posed (Linux)
- Git uses a standard process (Linux)
- Linux 4.0+ kernel support for hardware switching module (HW Switch Offload) (Linux)
- Linux --- manual release system cache (Linux)
- Security Knowledge: redirection command application security (Linux)
- Download Google Android source code under Ubuntu 4.4 (Linux)
- Tab set to four spaces in Vim (Linux)
- Safe learning through self-extracting package to achieve invasion (Linux)
- Get the Linux device PCI ID method (Linux)
- CentOS7 install MySQL5.6.22 (Linux)
- Git build a team development environment operating drills (Linux)
- Create a project using Android Studio LinearLayout (Programming)
- The Samba service does not have permission to access (Server)
- Linux non-root user uses less than 1024 ports (Linux)
- iOS persistence of data archiving NSKeyedArchiver (Programming)
- Red-black tree in C ++ (Programming)
- Production environment Linux bonding method standby mode slave card switch (Server)
- Linux system Perl Lite netstat (Linux)
- Linux can modify the maximum number of open files (Linux)
     
           
     
  CopyRight 2002-2022 newfreesoft.com, All Rights Reserved.