获取多线程及子线程的返回值是多线程编程中常用的操作,可以通过以下步骤实现:
- 定义一个线程函数
thread_func,且返回需要的结果。
def thread_func():
# 线程操作
return result
在这个函数中可以完成线程需要的操作,然后通过return返回需要的结果。
- 创建线程对象
thread。
thread = threading.Thread(target=thread_func, args=args)
其中 args 是线程函数需要的参数,可以是一个元组或者一个列表。
- 启动线程。
thread.start()
启动线程后,线程会在后台运行,这个时候可以获得线程的 ident(线程的唯一标识符),例如:
ident = thread.ident
- 等待子线程执行完毕。
thread.join()
在主线程中调用 join() 函数可以等待子线程执行完毕,保证程序的正确性。
- 获取子线程的返回值。
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!
The End


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)