[Learn Python with me] multiple threads in Python and multiple threads in python

Source: Internet
Author: User

[Learn Python with me] multiple threads in Python and multiple threads in python

In fact, I feel 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:

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 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:

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

 

 

 

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.I wonder if Doug Lea is involved in the development of this module. Haha ~~ (Purely YY), but there is only one more locked method than the LOCK class in JAVA, which is used to detect 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:

 

Python code
  1. Class Thread (_ Verbose ):
  2. _ 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:

 

 

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 will 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 shown in the figure, target points to a specific function object, and args passes in the required parameters 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:

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

 

 

 

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.

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

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.

Recommend a Website: program life


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.

Python Multithreading

That's of course. You can write it like this.
Self. p [:] = array

In this way, the pointer remains unchanged. Change content only. In this way, you can synchronize data.

Your writing method is to create an array and then use the pointer and ribbon self. p. If other threads have problems.

In addition, put your p before _ init. It is more reasonable to use T. p for reference.

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.