如何实现两函数并行运行,任一返回时终止另一函数?
问题描述
给定示例代码:
random_list = ['foo','foo','foo','foo',56,'foo','foo','foo','foo','foo'] # in random_list there are always 10 elements, one of which is 56, but its position is unknown def find_index_of_56_in_list_1(): for index in range(0,5): if 56 == random_list[index]: return index def find_index_of_56_in_list_2(): for index in range(6,10): if 56 == random_list[index]: return index
需将列表遍历任务拆分到两个线程,分别调用上述函数处理前后半段。要求:任一线程执行完毕返回结果时,立即终止另一线程,未完成的线程返回None。实际为更复杂计算任务的类比。
解决方案
Python的threading库没有安全的强制终止线程方法,推荐用**事件(Event)**实现协作式终止——让线程在执行中定期检查事件状态,触发后主动退出并返回None。
改造后代码示例
import threading random_list = ['foo','foo','foo','foo',56,'foo','foo','foo','foo','foo'] # 终止信号事件 stop_event = threading.Event() # 结果锁,保证线程安全写入 result_lock = threading.Lock() final_result = None def find_index_of_56_in_list_1(): global final_result for index in range(0,5): # 每次循环前检查是否需要停止 if stop_event.is_set(): return None if 56 == random_list[index]: with result_lock: final_result = index # 触发终止信号 stop_event.set() return index return None if stop_event.is_set() else None def find_index_of_56_in_list_2(): global final_result for index in range(6,10): if stop_event.is_set(): return None if 56 == random_list[index]: with result_lock: final_result = index stop_event.set() return index return None if stop_event.is_set() else None # 启动线程 t1 = threading.Thread(target=find_index_of_56_in_list_1) t2 = threading.Thread(target=find_index_of_56_in_list_2) t1.start() t2.start() # 等待线程结束 t1.join() t2.join() print(f"找到的索引: {final_result}") print(f"线程1返回值: {t1._return}") print(f"线程2返回值: {t2._return}")
核心逻辑
stop_event:作为跨线程的终止信号,一个线程找到结果后触发事件,另一个线程检测到信号后主动退出。result_lock:避免多线程同时写入final_result导致的竞态问题。- 主动检查机制:线程在每次循环迭代前检查事件状态,确保及时响应终止,这是Python中安全终止线程的标准方式(强制终止易引发资源泄漏或数据损坏)。
复杂场景适配提示
如果是更复杂的计算任务:
- 在合适的间隔插入终止检查(如每完成一个子任务、每迭代一次循环),避免检查间隔过长导致终止延迟。
- 若涉及阻塞IO,使用带
timeout的方法或结合select,防止线程卡在阻塞操作中无法响应终止信号。
内容的提问来源于stack exchange,提问作者Mezza
相关产品推荐
相关产品推荐

