溫馨提示×

python線程暫停和恢復的方法是什么

小億
278
2023-10-25 22:04:32
欄目: 編程語言

在Python中,可以使用threading模塊來創建和管理線程。在線程中,可以使用Event對象或者Condition對象來實現線程的暫停和恢復。

  1. 使用Event對象來實現線程的暫停和恢復:
    • 創建一個Event對象:event = threading.Event()
    • 在線程中使用event.wait()來暫停線程,直到收到信號。
    • 使用event.set()來發送信號,恢復線程。

示例代碼:

import threading
import time

def worker(event):
    print("Worker thread started")
    event.wait()  # 等待收到信號
    print("Worker thread resumed")
    # 執行其他操作

event = threading.Event()
t = threading.Thread(target=worker, args=(event,))
t.start()

time.sleep(2)  # 等待2秒

event.set()  # 發送信號,恢復線程
  1. 使用Condition對象來實現線程的暫停和恢復:
    • 創建一個Condition對象:condition = threading.Condition()
    • 在線程中使用condition.wait()來暫停線程,直到收到信號。
    • 使用condition.notify()或者condition.notifyAll()來發送信號,恢復線程。

示例代碼:

import threading
import time

def worker(condition):
    print("Worker thread started")
    with condition:
        condition.wait()  # 等待收到信號
    print("Worker thread resumed")
    # 執行其他操作

condition = threading.Condition()
t = threading.Thread(target=worker, args=(condition,))
t.start()

time.sleep(2)  # 等待2秒

with condition:
    condition.notify()  # 發送信號,恢復線程

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女