Python multithreaded Instance tutorial _python

Source: Internet
Author: User
Tags sleep thread class in python

In this paper, a more detailed explanation of Python's multithreading in the form of examples is a very important knowledge point in Python programming. Share for everyone to use for reference. The specific methods are as follows:

Anyone who has ever used python will find Python multithreading very similar to Java multithreading, but more flexible than Java multithreading. In the early Python multithreading implementation, the thread module was used. 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__": 
  main (); 

Briefly introduce the function function in this code block, sleep is the thread Morpheus time, almost equivalent to Thread.Sleep in Java (millionseconds)

Start_new_thread is the method that instantiates a thread and runs it, and the first parameter of the method accepts the function object that is executed by a thread while the second parameter is the parameter required to execute the method, which is passed in as a tuple.

This is probably the earliest Python multithreading implementation, and note that the main line in the Code Chengri Sleep (8). The sleeping time can only be bigger than 3+5, but not small. If it is less than this time, the main main thread exits prematurely, causing the thread interrupt exception to be thrown, regardless of whether its child thread is a background thread, which is similar to the Java threadinterruptexception. This lethal effect is almost always the culprit behind this module's late abandonment.

Of course, in the early Python multithreading, you could use the locking mechanism to avoid this. Slightly change the above code:

import thread; 
From time import sleep,ctime; 
From random import choice 
#The param means thread number #The second param means how 
long it sleep 
The third param means the Lock 
def Loop (nloop,sec,lock): 
  print "Thread", Nloop, "Start and'll 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__": 
  main (); 

This is where the Python thread is running with the lock monitoring mechanism, introducing several methods for the Red font flag (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 wonder if Doug Lea was involved in the development of this module, just a more method than the lock class in Java to detect whether the lock object is still in a locked state.

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

So the threading module is recommended in newer versions of Python.

Look 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 the thread is working properly or not.

The threading module supports three ways to create threads. The first two methods are related to the thread class. Take a look at its brief description:

Class Thread (_verbose): 
   __init__ (self, group=none, Target=none, Name=none, args= (), Kwargs=none, Verbose=none) 

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

The first method: Specifies the function to call 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'll 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 arguments necessary for the method call. A random sleep time is passed in here. Where thread.join means to wait for the thread to terminate, and Thread.Join (long millionseconds) in Java, it will wait until the specific time is specified.

The second approach is to specify a callable class instance, which 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'll 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__": 
  main (); 

This simply points to target from a function object to a callable class instance.

The

highlights the next third way, using inherited threading. Thread is the way to implement threads, have a Java multi-threaded application of friends will certainly be 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'll 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 (); 

As you can see from above, Mythread inherits the Threading.thread class and performs the necessary parameter assignment in the initialization method. It is worth noting that in the inheritance of the Java class, if the specified constructor for the parent class is not displayed, the default constructor method of the parent class is invoked. And in Python, it's not going to be called. So here you need to show the initialization method of the calling parent class.

I hope this article will help you with your Python programming.

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.