Pythonスレッドを一時停止および再開する方法

Pythonでは、スレッドの作成や管理にはthreadingモジュールを使います。スレッド内では、イベントオブジェクトまたは条件オブジェクトを使用してスレッドを停止または再開できます。

  1. イベント
  2. Eventオブジェクトの作成:event = threading.Event()
  3. スレッドでevent.wait()を使って、シグナルを受け取るまでスレッドを休止させる。
  4. イベント.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. もともと
  2. Condition インスタンスを作成します: condition = threading.Condition()
  3. スレッド内で`condition.wait()`を使用して、シグナルが届くまでスレッドを停止させます。
  4. 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()  # 发送信号,恢复线程
bannerAds