Python thread pause, resume, exit detail and Example _python

Source: Internet
Author: User
Tags mongodb postgresql redis thread stop in python

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.


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

    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()
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.

Alibaba Cloud Hot Products

Elastic Compute Service (ECS) Dedicated Host (DDH) ApsaraDB RDS for MySQL (RDS) ApsaraDB for PolarDB(PolarDB) AnalyticDB for PostgreSQL (ADB for PG)
AnalyticDB for MySQL(ADB for MySQL) Data Transmission Service (DTS) Server Load Balancer (SLB) Global Accelerator (GA) Cloud Enterprise Network (CEN)
Object Storage Service (OSS) Content Delivery Network (CDN) Short Message Service (SMS) Container Service for Kubernetes (ACK) Data Lake Analytics (DLA)

ApsaraDB for Redis (Redis)

ApsaraDB for MongoDB (MongoDB) NAT Gateway VPN Gateway Cloud Firewall
Anti-DDoS Web Application Firewall (WAF) Log Service DataWorks MaxCompute
Elastic MapReduce (EMR) Elasticsearch

Alibaba Cloud Free Trail

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