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

Python中同时运行函数与线程无法实现预期并发效果的问题求解

问题根因

  • 全局变量stop_threads初始值错误设置为True,线程启动后主函数第一次循环判断就会触发t1.join(),直接阻塞主函数执行,直到线程完全跑完才会继续主函数逻辑,所以看不到并发效果
  • 你把t1.join()放在了主函数的循环体内,只要stop_threads为True就会触发阻塞,完全打断了主函数的循环执行流程
  • 线程停止的标志位逻辑写反,导致线程跑完直接锁死主函数后续执行

修正后代码

import threading
from time import sleep

stop_threads = False  # 初始值改为False,不提前触发阻塞

def testthread():
    global stop_threads
    k = 0
    while k < 100 and not stop_threads:
        print("testthread -->", k)
        k += 1
        sleep(1)
    print('thread killed')

def testfunction():
    global stop_threads   
    t1 = threading.Thread(target = testthread)
    t1.start()
    i = 0
    while i < 100:
        print("testfunction-->", i)
        i += 1
        sleep(1)
        # 如需在满足特定条件时提前停止线程,可在此处添加判断逻辑设置stop_threads = True
    # 主函数循环结束后统一停止线程、等待线程退出
    stop_threads = True
    t1.join()

testfunction()

效果说明

修正后线程和主函数的循环会交替执行,每秒各打印一次计数,完全符合你要的并发输出效果。如果需要在主函数执行到某一步提前停止线程,在对应位置添加判断修改stop_threads值即可。

内容的提问来源于stack exchange,提问作者V_J viji

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 10:24:02