We all know that the threading module in python can implement multithreading, but the module does not provide methods for suspending, resuming and stopping threads. Once the thread object calls the start method, it can only wait until the corresponding method function is completed. That is to say, once start After that, the thread is out of control. However, we can achieve this by ourselves. The general method is to cyclically judge a flag bit, once the flag bit reaches a predetermined value, exit the loop. This will be able to exit the thread. But It is a bit difficult to pause and resume the thread. I have not cleared any good methods until I saw the description of the wait method of 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.
Block until the internal flag bit is True. If the internal flag bit is True when entering, return immediately. Otherwise, block until other threads call the set() method to set the standard bit to True, or reach the optional The timeout time.
When the timeout argument is present and not None, it should be a floating point number specifying a timeout for the operation in seconds (or fractions thereof).
This method returns the internal flag on exit, so it will always return True except if a timeout is given and the operation times out.
When the timeout parameter is given and not None, it should be a floating-point number that specifies the timeout (or fraction) of the operation in seconds.
This method returns an internal flag on exit, so unless a timeout is given and the operation times out, it will always return True.
Changed in version 2.7: Previously, the method always returned None.
Before version 2.7, this method always returned None.
Using the blocking mechanism of wait, you can pause and resume, and then cooperate with the cycle judgment flag to achieve exit. The following is a code example:
#!/usr/bin/env python
# coding: utf-8
import threading
import time
class Job(threading.Thread):
def __init__(self, *args, **kwargs):
super(Job, self).__init__(*args, **kwargs)
self.__flag = threading.Event() # The flag used to pause the thread
self.__flag.set() # Set to True
self.__running = threading.Event() # Used to stop the thread identification
self.__running.set() # Set running to True
def run(self):
while self.__running.isSet():
self.__flag.wait() # return immediately when it is True, block until the internal flag is True when it is False
print time.time()
time.sleep(1)
def pause(self):
self.__flag.clear() # Set to False to block the thread
def resume(self):
self.__flag.set() # Set to True, let the thread stop blocking
def stop(self):
self.__flag.set() # Resume the thread from the suspended state, if it is already suspended
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()
This completes the functions of pause, resume and stop. But there is a disadvantage: whether it is pause or stop, it is not instantaneous. It must wait for the internal operation of the run function to reach the flag to determine it. That is to say, the operation will lag once .
But this is not necessarily a bad thing sometimes. If the run function involves file operations or database operations, etc., run it once and then exit, but can execute the remaining resource release operation code (such as various closes). Nothing The file operator of the program exceeds the upper limit, and the database connection is not released.