Python multithreaded Instance Tutorial

Source: Internet
Author: User
This paper explains Python's multi-threading in detail, which is a very important knowledge point in Python program design. Share it for everyone's reference. Here's how:

People who have used python will find Python's multithreading very similar to the multithreading mechanism of Java, but more flexible than multithreading in Java. In the early Python multithreading implementation, the thread module was adopted. For example:

From time import ctime,sleep from thread import start_new_thread def loop1 ():   print "Enter Loop1:", CTime ();   Sleep (3);   Print "Leave Loop1:", CTime ();  Def loop2 ():   print "Enter Loop2:", CTime ();   Sleep (5);   Print "Leave Loop2:", CTime ();  def main ():   print "main begin:", CTime ();   Start_new_thread (Loop1, ());   Start_new_thread (Loop2, ());   Sleep (8);   Print "Main end:", CTime ();  If __name__== "__main__":   

A brief introduction to the function in this block of code, sleep is the thread sleeping time, almost equivalent to Thread.Sleep in Java (millionseconds)

Start_new_thread is a method that instantiates a thread and runs, the first parameter of the method accepts a function object executed by a thread at run time, and the second parameter is the parameter that is required when the method executes and is passed in as a tuple.

This is probably the earliest Python multithreading implementation, note the code in the main Line thread sleep (8). The sleeping time here can only be larger than 3+5, but not small. If it is less than this time, the main main thread exits prematurely, causing the thread break exception to be thrown, regardless of whether its child thread is a background thread, which is similar to Java's threadinterruptexception. This deadly effect is almost the culprit behind the late abandonment of this module.

Of course, in the early Python multi-threading, you can use the lock mechanism to avoid this situation. Change the above code slightly:

Import thread; From time import sleep,ctime; From random import choice #The first param means the thread number #The second param means how long it sleep #The third PA Ram means the Lock def Loop (nloop,sec,lock):   print "Thread", Nloop, "Start and would sleep", sec;   Sleep (sec);   Print "Thread", Nloop, "End", sec;   Lock.release ();  def main ():   seconds=[4,2];   Locks=[];   For I in range (len (seconds)):     Lock=thread.allocate_lock ();     Lock.acquire ();     Locks.append (lock);        Print "Main Thread begins:", CTime ();   For I,lock in Enumerate (locks):     Thread.start_new_thread (Loop, i,choice (seconds), lock));   For lock in Locks:     while lock.locked ():        Pass;   Print "Main Thread ends:", CTime ();  If __name__== "__main__":   

Here, the Python thread runs with a lock monitoring mechanism that introduces several methods of red font flags (in fact, the lock in the red font is the Thread.locktype instance.)

As you can see from the above introduction, this Lock class is very similar to the Java.util.concurrent.locks.Lock in JDK5.0. I don't know if Doug Lea was involved in the development of this module, just one more method locked than the lock class in Java, to detect if the lock object is still in a locked state.

So the previous example works by adding a lock to each thread when the thread is started, until the thread runs the description, and then releases the lock. At the same time, a while loop is used in the main thread of Python to constantly judge that each thread lock has been freed. Although this method avoids the artificial time control in the first example, it is not convenient and efficient.

Therefore, in newer versions of Python, it is recommended to use the threading module.

Looking at the API of the threading module, the Java development experience will find it very close to the Java.lang.Thread class. One thing to say here is that the threading Run method can return a function value, which is useful for tracking and judging whether a thread is running properly or not.

The threading module supports three methods of creating threads. The first two methods are related to their thread classes. Look at the brief description of it:

Class Thread (_verbose):    

Where target refers to a specific function, or a callable class instance (in this case, a class instance that implements the __call__ method)

The first method: Specifies the function called when the thread is running. Examples are as follows:

From time import ctime,sleep import threading; From random import choice  def loop (number,sec):   print "Thread", Number, "begins and would sleep", sec, "at", CTime ( );   Sleep (sec);   Print "Thread", Number, "ends at", CTime ();    def main ():   seconds=[2,4];   Threads=[];   Array=range (len (seconds));   For I in array:     t=threading. Thread (target=loop,args= (I,choice (seconds)));     Threads.append (t);   Print "Main Thread begins at", CTime ();   For T in Threads:     T.start ();   For T in Threads:     t.join ();       Print "Main Thread ends at", CTime ();  If __name__== "__main__":   main ();  

Here, target points to a specific function object, and args passes in the parameters necessary for the method invocation. Here comes an immediate sleep time. Where thread.join means to wait for the thread to terminate, as in Java Thread.Join (long millionseconds), if you do not specify a specific time, you will always wait.

The second method is to specify a callable class instance that is actually very close to the previous one. As shown below:

From time import ctime,sleep import threading; From random import Choice  class ThreadFunc (object):   def __init__ (self,func,args,name):     self.func=func;     Self.args=args;     Self.name=name;        def __call__ (self):     self.func (*self.args);  def loop (number,sec):   print "Thread", Number, "begins and would sleep", sec, "at", CTime ();   Sleep (sec);   Print "Thread", Number, "ends at", CTime ();    def main ():   seconds=[2,4];   Threads=[];   Array=range (len (seconds));   For I in array:     t=threading. Thread (Target=threadfunc (Loop, (I,choice (seconds)), loop.__name__));     Threads.append (t);   Print "Main Thread begins at", CTime ();   For T in Threads:     T.start ();   For T in Threads:     t.join ();       Print "Main Thread ends at", CTime ();  If __name__== "__main__":   

This is just pointing at Target from a function object into a callable class instance.

The third approach, with inheritance threading, is the key recommendation. Thread way to implement threading, a friend of the Java multithreaded application will be very familiar with the following example.

From time import ctime,sleep import threading; From random import Choice  class MyThread (threading. Thread):   def __init__ (self,func,args,name):     super (Mythread,self). __init__ ();     Self.func=func;     Self.args=args;     Self.name=name;          def run (self):     self.result=self.func (*self.args);    def getresult (self):     return self.result;    def loop (number,sec):   print "Thread", Number, "begins and would sleep", sec, "at", CTime ();   Sleep (sec);   Print "Thread", Number, "ends at", CTime ();    def main ():   seconds=[2,4];   Threads=[];   Array=range (len (seconds));   For I in array:     T=mythread (Loop, (I,choice (seconds)), loop.__name__);     Threads.append (t);   Print "Main Thread begins at", CTime ();   For T in Threads:     T.start ();   For T in Threads:     t.join ();       Print "Main Thread ends at", CTime ();  If __name__== "__main__":   main ();   

It can be seen from the above that Mythread inherits the Threading.thread class and performs the necessary parameter assignment in the initialization method. It is important to note that in the case of Java class inheritance, if you do not display the constructor method that specifies calling the parent class, the default constructor method of the parent class is called. In Python, there is no initiative to invoke. So here we need to show the initialization method of calling the parent class.

Hopefully this article will help you with Python programming.

  • 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.