You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何并行运行含等待逻辑的方法,使任意玩家可率先输出结果?

解决同步阻塞导致玩家输出顺序固定的问题

嘿,你遇到的核心问题是代码同步执行带来的阻塞:当前saySnap("p1")会先完整跑完(包括sleep的时间),才会开始执行saySnap("p2"),所以p1必然先输出。要让两个玩家真正随机竞争输出顺序,咱们得用多线程让它们的任务并行起来!

方案1:使用threading模块创建独立线程

直接给每个玩家分配一个独立线程,这样它们的sleep操作只会阻塞自己的线程,不会互相影响:

import time
import random
import threading

def saySnap(player):
    reactionTime = random.randint(120, 401) / 1000
    time.sleep(reactionTime)
    print("{} : Snap!".format(player))

# 为每个玩家创建线程
player_threads = [
    threading.Thread(target=saySnap, args=("p1",)),
    threading.Thread(target=saySnap, args=("p2",))
]

# 启动所有线程
for thread in player_threads:
    thread.start()

# 可选:等待所有线程执行完毕再结束主程序
for thread in player_threads:
    thread.join()

运行这段代码,你会看到p1和p2的输出顺序是随机的——谁的随机反应时间更短,谁就先打印结果。

方案2:用ThreadPoolExecutor简化多线程管理

如果后续需要扩展更多玩家,用concurrent.futures里的线程池会更简洁:

import time
import random
from concurrent.futures import ThreadPoolExecutor

def saySnap(player):
    reactionTime = random.randint(120, 401) / 1000
    time.sleep(reactionTime)
    print("{} : Snap!".format(player))

# 用线程池批量提交任务
with ThreadPoolExecutor(max_workers=2) as executor:
    executor.submit(saySnap, "p1")
    executor.submit(saySnap, "p2")

线程池会自动帮你管理线程的创建和回收,代码更简洁易维护。

为什么这个方法有效?

同步代码是按顺序执行的,前一个任务没完成,后一个就没法开始。而多线程能让多个任务同时启动,各自的time.sleep只会暂停自己的执行流程,不会卡住其他任务。这样两个玩家的反应时间是真正并行计算的,输出顺序完全由随机生成的reactionTime决定。

内容的提问来源于stack exchange,提问作者Danny G

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 12:52:48