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

如何通过线程与无限循环持续返回值 独立获取金融资产最新价格

多线程实现无限轮询拉取价格不阻塞主流程的方案

核心逻辑

你遇到的核心问题是运行无限循环的线程永远不会走到return语句,所以不能通过常规的线程返回值拿结果,用线程安全的共享存储来传递最新价格即可,整体逻辑如下:

  • 把无限循环发GET请求的逻辑放到独立子线程运行,和主业务逻辑完全隔离
  • 用共享变量/队列存每次拉取到的最新价格,子线程负责更新,主业务逻辑直接读取即可
  • 新增退出标志位,需要时可以优雅终止轮询线程,避免程序退出时卡死

可运行示例代码(Python)

import threading
import requests
import time

# 存储最新价格的共享变量
latest_price = None
# 线程退出标志位
stop_polling = threading.Event()
# 读写共享变量的锁,保证线程安全
price_lock = threading.Lock()

def poll_price():
    """子线程执行的价格拉取逻辑"""
    global latest_price
    while not stop_polling.is_set():
        try:
            # 替换为实际的金融数据接口地址
            resp = requests.get("YOUR_API_URL", timeout=5)
            resp.raise_for_status()
            # 替换为实际的接口返回字段解析逻辑
            new_price = resp.json()["asset_price"]
            # 更新共享变量
            with price_lock:
                latest_price = new_price
            # 调整请求间隔,避免被接口限流
            time.sleep(1)
        except Exception as e:
            print(f"拉取价格失败,重试中:{str(e)}")
            time.sleep(2)

if __name__ == "__main__":
    # 启动轮询子线程,设为守护线程,主程序退出时自动销毁
    price_thread = threading.Thread(target=poll_price, daemon=True)
    price_thread.start()
    start_time = time.time()

    # 这里写你的主业务逻辑,完全不会被轮询操作阻塞
    while True:
        # 读取最新价格
        with price_lock:
            current_price = latest_price
        
        if current_price:
            # 你的业务处理逻辑,比如计算指标、下单等
            print(f"当前资产价格:{current_price}")
        else:
            print("正在拉取首次价格...")
        
        # 模拟业务逻辑执行间隔
        time.sleep(0.5)

        # 示例:运行30秒后优雅退出
        if time.time() - start_time > 30:
            stop_polling.set()
            price_thread.join()
            print("程序终止")
            break

关键注意事项

  • 线程安全优先:如果只有一个子线程写价格、其他线程只读,简单类型的读写是原子的,复杂结构或者多写场景必须加锁,避免读到脏数据
  • 必须加异常捕获和超时:避免接口异常直接导致拉取线程崩溃,后续无法更新价格
  • 如果你需要处理每一次价格更新(而不是只需要最新值),可以用queue.Queue代替共享变量,子线程拉到价格就写入队列,业务线程阻塞/非阻塞从队列取数据即可
  • 轮询间隔根据你的实时性需求调整,不要无限制高频请求,避免被接口服务商限流

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 16:15:04