共計 912 個字符,預(yù)計需要花費 3 分鐘才能閱讀完成。
在 Python 中,可以使用 threading 模塊來創(chuàng)建和管理線程。在線程中,可以使用 Event 對象或者 Condition 對象來實現(xiàn)線程的暫停和恢復(fù)。
- 使用
Event對象來實現(xiàn)線程的暫停和恢復(fù):- 創(chuàng)建一個
Event對象:event = threading.Event() - 在線程中使用
event.wait()來暫停線程,直到收到信號。 - 使用
event.set()來發(fā)送信號,恢復(fù)線程。
- 創(chuàng)建一個
示例代碼:
import threading
import time
def worker(event):
print("Worker thread started")
event.wait() # 等待收到信號
print("Worker thread resumed")
# 執(zhí)行其他操作
event = threading.Event()
t = threading.Thread(target=worker, args=(event,))
t.start()
time.sleep(2) # 等待 2 秒
event.set() # 發(fā)送信號,恢復(fù)線程
- 使用
Condition對象來實現(xiàn)線程的暫停和恢復(fù):- 創(chuàng)建一個
Condition對象:condition = threading.Condition() - 在線程中使用
condition.wait()來暫停線程,直到收到信號。 - 使用
condition.notify()或者condition.notifyAll()來發(fā)送信號,恢復(fù)線程。
- 創(chuàng)建一個
示例代碼:
import threading
import time
def worker(condition):
print("Worker thread started")
with condition:
condition.wait() # 等待收到信號
print("Worker thread resumed")
# 執(zhí)行其他操作
condition = threading.Condition()
t = threading.Thread(target=worker, args=(condition,))
t.start()
time.sleep(2) # 等待 2 秒
with condition:
condition.notify() # 發(fā)送信號,恢復(fù)線程
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完