Pythonスレッドを一時停止および再開する方法
Pythonでは、スレッドの作成や管理にはthreadingモジュールを使います。スレッド内では、イベントオブジェクトまたは条件オブジェクトを使用してスレッドを停止または再開できます。
- イベント
- Eventオブジェクトの作成:event = threading.Event()
- スレッドでevent.wait()を使って、シグナルを受け取るまでスレッドを休止させる。
- イベント.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() # 发送信号,恢复线程
- もともと
- 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() # 发送信号,恢复线程