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

Python多线程UDP服务器线程无法并行仅单线程启动如何修复

问题原因

你创建线程时对target参数的赋值逻辑错误:

  • threading.Thread的target参数需要接收可调用对象的引用,而你写的target=task_putter()会在主线程中直接同步执行task_putter函数,不会把函数交给子线程运行
  • 由于task_putter内部是无限循环,主线程执行到这一行就会被永久阻塞,后续创建action_thread、启动线程的代码完全不会执行,因此只输出了Hello Task,第二个线程从未被创建启动
修复方案

把创建线程时target参数后函数的调用括号去掉,只传递函数名本身即可,修改后的代码如下:

def action_assigner():
    print('Hello Assign')
    while True:
        if work_queue.qsize() != 0:
            data, client_address, request_number = work_queue.get()
            do_actions(data, client_address, request_number)


def task_putter():
    request_number = 0
    print('Hello Task')
    while True:
        data_received = server_socket.recvfrom(1024)
        request_number += 1
        taskRunner(data_received, request_number)


try:
    # 去掉target后面函数的括号,只传函数引用
    thread_task = threading.Thread(target=task_putter)
    action_thread = threading.Thread(target=action_assigner)

    action_thread.start()
    thread_task.start()

    action_thread.join()
    thread_task.join()


except Exception as e:
    server_socket.close()
补充说明
  • 如果你的函数需要传递参数,可以用threading.Thread的args参数传入,示例:threading.Thread(target=func, args=(param1, param2))
  • Queue的get()方法本身就是阻塞的,不需要提前判断qsize(),可以直接写work_queue.get(),能避免空轮询消耗CPU资源

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 22:45:08