"Learn Python with me" python multithreading

Source: Internet
Author: User

In fact, the self-feeling Python multithreading is similar to the multithreading mechanism of Java, but more flexible than Java multithreading. In the early Python multithreading implementation, the thread module was adopted. For example:

Python code
  1. From time import Ctime,sleep
  2. From thread import start_new_thread
  3. Def LOOP1 ():
  4. print "Enter Loop1:", CTime ();
  5. Sleep (3);
  6. print "Leave Loop1:", CTime ();
  7. Def LOOP2 ():
  8. print "Enter LOOP2:", CTime ();
  9. Sleep (5);
  10. print "Leave loop2:", CTime ();
  11. def main ():
  12. print "main begin:", CTime ();
  13. Start_new_thread (Loop1, ());
  14. Start_new_thread (Loop2, ());
  15. Sleep (8);
  16. print "main end:", CTime ();
  17. If __name__=="__main__":
  18. 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:

Python code
  1. Import thread;
  2. From time import sleep,ctime;
  3. From random import Choice
  4. #The first param means the thread number
  5. #The second param means how long it sleep
  6. #The third param means the Lock
  7. def loop (Nloop,sec,lock):
  8. print "Thread", Nloop,"Start and would sleep", sec;
  9. Sleep (sec);
  10. print "Thread", Nloop,"End", sec;
  11. Lock.release ();
  12. def main ():
  13. seconds=[4,2];
  14. Locks=[];
  15. For I in range (len (seconds)):
  16. Lock=thread.allocate_lock ();
  17. Lock.acquire ();
  18. Locks.append (lock);
  19. print "main Thread begins:", CTime ();
  20. For I,lock in Enumerate (locks):
  21. Thread.start_new_thread (Loop, (I,choice (seconds), lock));
  22. For lock in locks:
  23. While lock.locked ():
  24. Pass;
  25. print "main Thread Ends:", CTime ();
  26. If __name__=="__main__":
  27. 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 in JDK5.0. Lock. don't know if Doug Lea is involved in the development of this module, haha ~ ~ (purely yy), just more than the lock class in Java a method locked, to detect whether the lock object is still in the lock 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:

Python code
    1. Class Thread (_verbose):
    2. __init__ (self, group=None, target=None, Name=None, args= (), kwargs=None, verbose=None) /c6>

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:

Python code
  1. From time import Ctime,sleep
  2. Import threading;
  3. From random import Choice
  4. def loop (number,sec):
  5. print "Thread", Number,"begins and would sleep", sec,"at", CTime ();
  6. Sleep (sec);
  7. print "Thread", Number,"ends at", CTime ();
  8. def main ():
  9. seconds=[2,4];
  10. Threads=[];
  11. Array=range (len (seconds));
  12. For i in array:
  13. T=threading. Thread (target=loop,args= (I,choice (seconds)));
  14. Threads.append (t);
  15. print "main Thread begins at", CTime ();
  16. For T in Threads:
  17. T.start ();
  18. For T in Threads:
  19. T.join ();
  20. print "main Thread ends at", CTime ();
  21. If __name__=="__main__":
  22. Main ();

As can be seen here, target points to a specific function object, and args passes 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:

Python code
  1. From time import Ctime,sleep
  2. Import threading;
  3. From random import Choice
  4. Class ThreadFunc (object):
  5. def __init__ (self,func,args,name):
  6. Self.func=func;
  7. Self.args=args;
  8. Self.name=name;
  9. def __call__ (self):
  10. Self.func (*Self.args);
  11. def loop (number,sec):
  12. print "Thread", Number,"begins and would sleep", sec,"at", CTime ();
  13. Sleep (sec);
  14. print "Thread", Number,"ends at", CTime ();
  15. def main ():
  16. seconds=[2,4];
  17. Threads=[];
  18. Array=range (len (seconds));
  19. For i in array:
  20. T=threading. Thread (Target=threadfunc (Loop, (I,choice (seconds)), loop.__name__));
  21. Threads.append (t);
  22. print "main Thread begins at", CTime ();
  23. For T in Threads:
  24. T.start ();
  25. For T in Threads:
  26. T.join ();
  27. print "main Thread ends at", CTime ();
  28. If __name__=="__main__":
  29. 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.

Python code
  1. From time import Ctime,sleep
  2. Import threading;
  3. From random import Choice
  4. Class MyThread (threading. Thread):
  5. def __init__ (self,func,args,name):
  6. Super (MyThread, Self). __init__ ();
  7. Self.func=func;
  8. Self.args=args;
  9. Self.name=name;
  10. def run (self):
  11. self.result=Self.func (*Self.args);
  12. def getresult (self):
  13. return Self.result;
  14. def loop (number,sec):
  15. print "Thread", Number,"begins and would sleep", sec,"at", CTime ();
  16. Sleep (sec);
  17. print "Thread", Number,"ends at", CTime ();
  18. def main ():
  19. seconds=[2,4];
  20. Threads=[];
  21. Array=range (len (seconds));
  22. For i in array:
  23. T=mythread (Loop, (I,choice (seconds)), loop.__name__);
  24. Threads.append (t);
  25. print "main Thread begins at", CTime ();
  26. For T in Threads:
  27. T.start ();
  28. For T in Threads:
  29. T.join ();
  30. print "main Thread ends at", CTime ();
  31. If __name__=="__main__":
  32. 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.

Recommend a website: program life

"Learn Python with me" python 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.