Python thread pause, resume, exit details and examples

Source: Internet
Author: User
Tags thread stop

python thread paused, resumed, exited

We all know that Python can be a threading module to implement multi-threading, but the module does not provide a way to pause, resume, and stop threads, Once the thread object calls the Start method, it can only wait until the corresponding method function has finished running. This means that once start, the thread is out of control. However, we can do this ourselves. The general method is to iterate over a flag bit and exit the loop once the flag reaches the predetermined value. This will make it possible to exit the thread. But pausing and resuming threads is a bit difficult, and I've never cleaned up any good methods until I see the description of the wait method for the event object in threading.

Wait ([timeout])  Block until the internal flag is true. If the internal flag is true on entry, return immediately. Otherwise, block until another thread calls set () to set the flag to true, or until the optional timeout occurs.  Blocks until the internal flag bit is true. Returns immediately if the internal flag bit is true at the time of entry. Otherwise, blocking until other threads call the set () method sets the standard bit to true, or the optional timeout time is reached.  When the timeout argument was present and not None, it should was a floating point number specifying a timeout for the opera tion in seconds (or fractions thereof).  This method returns the internal flag on exit, so it would always return True except if a timeout is given and the Operatio N times out.  When the timeout parameter is given and is not none, it should be a floating-point number that specifies the time-out (or fraction) of the operation in seconds.  This method returns an internal flag on exit, so it always returns true unless a timeout is given and the operation times out.  Changed in version 2.7:previously, the method is always returned None.  Until version 2.7, this method always returns none.



By using the blocking mechanism of wait, it is possible to implement pause and resume, and then match the loop to determine the identity bit, you can implement the exit, the following is the code example:

#!/usr/bin/env python# coding:utf-8import threadingimport timeclass Job (threading. Thread):  def __init__ (self, *args, **kwargs):    super (Job, self). __init__ (*args, **kwargs)    Self.__flag = Threading. Event ()   # is used to pause the thread's identity    Self.__flag.set ()    # set to True    self.__running = threading. Event ()   # to stop the thread's identity    Self.__running.set ()   # Set Running to True  def run (self): while    self.__ Running.isset ():      self.__flag.wait ()   # is True when returned immediately, false when blocking until the internal identity bit is true after returning to      print Time.time ()      time.sleep (1)  def pause (self):    self.__flag.clear ()   # set to False to have the thread block  def resume (self):    Self.__flag.set ()  # set to True to let the thread stop blocking  def stop (self):    self.__flag.set ()    # Restores the thread from the paused state, How to pause    the words self.__running.clear ()    # set to False



Here is the test code:

A = Job () A.start () Time.sleep (3) A.pause () Time.sleep (3) A.resume () Time.sleep (3) A.pause () Time.sleep (2) a.stop ()



Results of the test:




This completes the pause, resume, and stop functions. But here's a drawback: whether it's a pause or a stop, it's not instantaneous, it has to wait for the run inside of the function to arrive at the flag bit to determine the validity. This means that the operation is delayed one time.

But this is sometimes not necessarily a bad thing. If the run function involves file operations or database operations, and so on, and then exits completely once, it is possible to execute the remaining code of the resource release operation (for example, various close). The program's file operator does not appear to exceed the upper limit, the database connection is not released, and other embarrassing situations.

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.