python获取多线程及子线程的返回值

  

获取多线程及子线程的返回值是多线程编程中常用的操作,可以通过以下步骤实现:

  1. 定义一个线程函数 thread_func,且返回需要的结果。
def thread_func():
    # 线程操作
    return result

在这个函数中可以完成线程需要的操作,然后通过return返回需要的结果。

  1. 创建线程对象 thread
thread = threading.Thread(target=thread_func, args=args)

其中 args 是线程函数需要的参数,可以是一个元组或者一个列表。

  1. 启动线程。
thread.start()

启动线程后,线程会在后台运行,这个时候可以获得线程的 ident(线程的唯一标识符),例如:

ident = thread.ident
  1. 等待子线程执行完毕。
thread.join()

在主线程中调用 join() 函数可以等待子线程执行完毕,保证程序的正确性。

  1. 获取子线程的返回值。
result = thread_func.result

thread_func 函数中,我们已经使用 return 返回了需要的结果,因此可以直接通过线程对象的一个属性获取线程执行后的结果。

下面是两个获取子线程返回值的示例。

示例一

import threading

def thread_func():
    # 线程操作
    return "Success"

thread = threading.Thread(target=thread_func)
thread.start()
thread.join()

result = thread_func.result
print(result)

输出:

Success

示例二

import threading

def thread_func(name):
    # 线程操作
    return "Hello, %s!" % name

thread = threading.Thread(target=thread_func, args=("Tom",))
thread.start()
thread.join()

result = thread_func.result
print(result)

输出:

Hello, Tom!
相关文章