Python multi-thread instance tutorial and python instance tutorial

Source: Internet
Author: User

Python multi-thread instance tutorial and python instance tutorial

This article describes in detail the multithreading of Python in the form of examples, which is a very important knowledge point in Python programming. Share it with you for your reference. The specific method is as follows:

Anyone who has used Python will think that Python multithreading is similar to Java's multithreading mechanism, but it is more flexible than JAVA's multithreading. In the early implementation of Python multithreading, 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(); 

A Brief Introduction to the function functions in this code block. sleep is the Thread sleep time, which is almost equivalent to Thread. sleep (millionseconds) in JAVA)

Start_new_thread is the method for instantiating a thread and running it. The first parameter of the method accepts the function object executed during the running of the thread, and the second parameter is the parameter required for the method execution, input in the form of a tuples.

This is probably the earliest multi-threaded Python implementation. Pay attention to sleep (8) in the main thread in the code ). The sleep time here is only 3 + 5, not small. If it is less than this time, the main thread will exit early, resulting in thread interruption exceptions, similar to ThreadInterruptException in Java, regardless of whether its sub-thread is a background thread. This fatal impact is almost the culprit of this module being abandoned later.

Of course, in the early versions of Python multithreading, you can use the locking mechanism to avoid this situation. Slightly modify the above Code:

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 param means the Lock def loop(nloop,sec,lock):   print "Thread ",nloop," start and will 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(); 

The lock monitoring mechanism is added to the Python thread runtime to introduce several methods of red font mark (in fact, the lock in red font is actually a thread. lockType instance.

From the above introduction, we can see that this Lock class is very similar to java. util. concurrent. locks. Lock in JDK5.0. I don't know if Doug Lea is involved in the development of this module. It just has a method locked more than the LOCK class in JAVA to check whether the Lock Object is still locked.

Therefore, the working principle of the previous example is to add a lock to each thread when starting the thread until the thread is introduced and then released. At the same time, A while LOOP is used in the main thread of Python to continuously judge that each thread lock has been released. Although this method avoids human time control in the first example, it is not convenient and efficient.

Therefore, the threading module is recommended in newer Python versions.

Check the threading module API. If you have JAVA development experience, you will find that it is very similar to the java. lang. Thread class. One thing to mention here is that the threading run method can return the function value, which is very useful in tracking and determining whether the thread is running normally.

The threading module supports three methods to create threads. The first two methods are related to the Thread class. Let's take a look at its brief description:

class Thread(_Verbose) :    __init__(self, group=None, target=None, name=None, args=(), kwargs=None, verbose=None) 

Specifically, target refers to a specific function or a callable class instance (here it refers to a class instance that implements the _ call _ method)

Method 1: Specify the function called when the thread is running. Example:

from time import ctime,sleep import threading; from random import choice  def loop(number,sec):   print "Thread ",number," begins and will 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 required for this method call. A sleep time is introduced here. Thread. join indicates that the Thread is waiting for termination, which is the same as thread. join (long millionseconds) in java. If no specific time is specified, the Thread will remain waiting.

The second method is to specify an callable class instance, which is actually very close to the previous one. As follows:

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

Here, the target is directed from a function object to a callable class instance.

We recommend the third method to implement the Thread by inheriting threading. Thread. If you have a Java multi-threaded application, you will 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 will 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();   

From the above, we can see that MyThread inherits the threading. Thread class and executes necessary parameter values in the initialization method. It is worth noting that, in the inheritance of Java classes, if you do not specify to call the constructor of the parent class, the non-argument constructor of the parent class will be called by default. In Python, it does not take the initiative to call. Therefore, the initialization method of the parent class needs to be displayed here.

I hope this article will help you with Python programming.


What is the problem with this small example of python multithreading?

It should be because your variable name and class name are the same that the program cannot tell whether your sellThread is a class or a variable.

Change your variable name.

Multithreading in Python

Python GIL requires that only one thread can access the python virtual machine at a time. Therefore, it is not worthwhile to use multiple threads of python for computing. However, for IO-intensive applications, such as network interaction, the multithreading of python is still very powerful.
If you are a computing-intensive task and must use python for parallel execution, you can use the following methods:
1. Use the python multiprocessing module to take advantage of multiple cores.
2. ironPython is used, but this can only be used in windows.
3. Use pypy to implement real multithreading.

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.