python 实现线程的暂停, 恢复, 退出详解及实例

这篇博客介绍了如何在Python的多线程环境中使用threading模块的Event对象来实现线程的暂停、恢复和停止。通过设置标志位并结合wait方法,可以精确控制线程的执行流程。示例代码展示了如何创建Job类,该类的实例可以在运行过程中被暂停、恢复和停止。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Python中可以是threading模块实现多线程, 但是模块并没有提供暂停, 恢复和停止线程的方法, 一旦线程对象调用start方法后, 只能等到对应的方法函数运行完毕. 也就是说一旦start后, 线程就属于失控状态. 对于函数中没有循环,可以使用join()来结束循环。
其中方法之一:一般的方法就是循环地判断一个标志位, 一旦标志位到达到预定的值, 就退出循环. 这样就能做到退出线程了. threading中Event对象能实现此功能。

  • 对于event.isSet()可以查看event的状态,
  • set()函数返回为True,
  • clear()函数返回为False。
  • self.__flag.wait() 中self.__flag为True时立即返回, 为False时阻塞直到self.__flag为True后返回
    另一个方法是使用信号量。
    def wait(self, timeout=None):
        """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.
		阻塞, 直到内部的标志位为True时. 如果在内部的标志位在进入时为True时, 立即返回. 否则, 阻塞直到其他线程调用set()方法将标准位设为True, 或者到达了可选的timeout时间.
        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).
		当给定了timeout参数且不为None, 它应该是一个浮点数,以秒为单位指定操作的超时(或是分数)。
		此方法在退出时返回内部标志,因此除非给定了超时且操作超时,否则它将始终返回True。
        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.
        """
        ......

利用wait的阻塞机制, 就能够实现暂停和恢复了, 再配合循环判断标识位, 就能实现退出了, 下面是代码示例:

#!/usr/bin/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()   
    self.__flag.set()    # 设置为True
    # 用于停止线程的标识
    self.__running = threading.Event()   
    self.__running.set()   # 将running设置为True

  def run(self):
    while self.__running.isSet():
      self.__flag.wait()   # 为True时立即返回, 为False时阻塞直到内部的标识位为True后返回
      print time.time()
      time.sleep(1)

  def pause(self):
    self.__flag.clear()   # 设置为False, 让线程阻塞

  def resume(self):
    self.__flag.set()  # 设置为True, 让线程停止阻塞

  def stop(self):
    self.__flag.set()    # 将线程从暂停状态恢复, 如果已经暂停的话
    self.__running.clear()    # 设置为False  
### 回答1: Python中的线程可以使用`time.sleep()`函数来暂停线程的执行。例如: ```python import threading import time def worker(): print("Worker thread started") time.sleep(5) # 暂停5秒钟 print("Worker thread resumed") t = threading.Thread(target=worker) t.start() print("Main thread started") time.sleep(2) # 暂停2秒钟 print("Main thread resumed") ``` 输出: ``` Main thread started Worker thread started Main thread resumed Worker thread resumed ``` 在上面的例子中,主线程工作线程都会暂停一段时间,然后继续执行。注意,`time.sleep()`函数会阻塞当前线程的执行,因此在实际应用中应该避免过长的暂停时间,以免影响程序的响应性能。 ### 回答2: 在Python中,使用threading模块创建的线程可以通过调用sleep()方法来暂停线程。该方法可以将线程挂起指定的时间,之后线程会自动恢复并继续执行。 除了使用sleep()方法暂停线程外,还可以使用Event对象或Condition对象来实现线程暂停恢复。Event对象用于线程间的同步,可以用来发送信号,使一个或多个线程暂停恢复。Condition对象也用于线程间的同步,但它更为灵活,可以根据条件来暂停恢复线程。 以下是Python中三种暂停线程的方法的示例: 1.使用sleep()方法暂停线程: import threading def run(): print('Start') # 暂停线程2秒 threading.Thread.sleep(2) print('End') if __name__ == '__main__': t = threading.Thread(target=run) t.start() 2.使用Event对象暂停线程: import threading def worker(event): print('Worker: Waiting for event') event.wait() print('Worker: Event set') def main(): # 创建事件对象 event = threading.Event() # 创建线程 t = threading.Thread(target=worker, args=(event,)) # 启动线程 t.start() # 2秒后设置事件 threading.Thread.sleep(2) print('Main: Setting event') event.set() if __name__ == '__main__': main() 3.使用Condition对象暂停线程: import threading class Worker(threading.Thread): def __init__(self, cond): threading.Thread.__init__(self) self.cond = cond def run(self): # 等待条件变为True with self.cond: self.cond.wait() print('Worker: Condition is set') # 继续执行 print('Worker: Done') def main(): # 创建条件对象 cond = threading.Condition() # 创建线程 t = Worker(cond) # 启动线程 t.start() # 2秒后设置条件为True threading.Thread.sleep(2) with cond: cond.notify() if __name__ == '__main__': main() 总而言之,Python线程暂停恢复可以通过sleep()方法、Event对象Condition对象来实现。具体使用哪种方法取决于你的需求,不同的方法可以提供不同的灵活性粒度。 ### 回答3: Python中的线程Thread)是指在某个进程中的一条执行序列,它可以在同一时间内运行多个不同的线程,并且它们之间是并发执行的。就像在现实生活中,我们常常需要暂停工作一段时间,去休息、思考或处理其他事情一样。Python threading模块提供了一些方法来暂停恢复线程,使我们的程序能够更好地解决问题。 暂停线程的方法: Python中提供了一些方法来暂停线程,最常用的是time模块的sleep()方法。调用sleep()方法会导致当前线程暂停执行一段时间,让其他线程有机会执行。 下面是使用sleep()方法暂停线程的一个示例: ```python import threading import time def print_number(): for i in range(1, 11): print(i) time.sleep(1) if __name__ == "__main__": thread = threading.Thread(target=print_number) thread.start() ``` 在这个示例中,我们创建了一个名为print_number()的方法,并使用线程来运行它。方法执行了一个循环,打印数字1到10,并使用time.sleep(1)方法在每次迭代之间暂停1秒。线程在执行完这个方法之后退出。 除了使用sleep()方法之外,Python threading模块还提供了其他一些方法来暂停线程,例如join()方法Condition对象的wait()方法。 join()方法可以等待一个线程完成。当一个线程在执行join()时,其他线程将被阻塞,直到该线程完成执行。例如: ```python import threading def print_number(): for i in range(1, 11): print(i) if __name__ == "__main__": thread = threading.Thread(target=print_number) thread.start() # 等待线程执行完毕 thread.join() print("Done") ``` 在这个示例中,我们创建了一个名为print_number()的方法,它打印数字1到10。我们使用join()方法等待线程执行完毕,然后输出“Done”。 wait()方法是Condition对象的方法之一,它可以使线程等待,直到另一个线程调用notify()或notify_all()方法。Condition对象用于线程之间的协调。例如: ```python import threading class Calculator: def __init__(self): self.total = 0 self.cond = threading.Condition() def add(self, num): with self.cond: self.total += num self.cond.notify() def get_total(self): with self.cond: while self.total == 0: self.cond.wait() return self.total if __name__ == "__main__": calc = Calculator() calc_thread = threading.Thread(target=calc.get_total) calc_thread.start() calc_thread.join() ``` 在这个示例中,我们使用了一个Calculator类,它有一个add()方法一个get_total()方法。我们创建了一个名为calc_thread线程,并让它调用get_total()方法。get_total()方法在计算器的total值为0时等待(使用Condition对象的wait()方法),直到其他线程调用了add()方法并修改了total的值(使用notify()方法),get_total()方法才返回total的值。 以上是Python threading暂停线程的一些方法示例。我们可以根据具体需求选择适合的方法,使我们的程序更加高效、简洁。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值