python多线程中获取函数返回值的三种方法

 更新时间:2023年03月01日 15:49:01   作者:深夜键盘侠  
本文主要介绍了python多线程中获取函数返回值的三种方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

方法一:使用队列

import queue
import threading
import sys
import time
 
q=queue.Queue()
def func1(x,y):
    func_name = sys._getframe().f_code.co_name # 获取函数名
    print("%s run ....." % func_name)
    q.put((x+y,func_name))
 
def func2(x,y):
    func_name = sys._getframe().f_code.co_name
    print("%s run ...." %func_name)
    q.put((x-y,func_name))
 
if __name__ == "__main__":
    result=[]
    t1=threading.Thread(target=func1,name="thread1",args=(10,5))
    t2=threading.Thread(target=func2,name="thread2",args=(20,1))
    print('*'*20)
    t1.start()
    t2.start()
    t1.join()
    t2.join()
    while not q.empty():# 队列为空返回True,反之False
        result.append(q.get())
    for item in result:
        if item[1] == func1.__name__:
            print("%s return value is: %s" %(item[1],item[0]))
        elif item[1] == func2.__name__:
            print("%s return value is: %s" %(item[1],item[0]))

运行结果:
********************
func1 run .....
func2 run ....
func1 return value is: 15
func2 return value is: 19

方法二: 封装 threading.Thread,重写 run 方法

class mythread(threading.Thread):
    def __init__(self,func,args=()):
        super(mythread, self).__init__()
        self.func=func
        self.args=args
    def run(self):
        self.result=self.func(*self.args)
    def get_result(self):
        try:
            return self.result
        except Exception:
            return None
def foo(a,b,c):
    time.sleep(1)
    return a*2,b*2,c*2
li = []
for i in range(4):
    t=mythread(foo,args=(i,i+1,i+2))
    li.append(t)
    t.start()
for t in li:
    t.join()
    print(t.get_result())
 
# 运行结果
(0, 2, 4)
(2, 4, 6)
(4, 6, 8)
(6, 8, 10)

方法三:使用进程池

def func(msg):
    print("msg:",msg)
    time.sleep(3)
    print("end")
    return "done" + msg
if __name__ == "__main__":
    pool = multiprocessing.Pool(processes=4)
    result = []
    for i in range(3):
        msg = "hello %d" %i
        result.append(pool.apply_async(func,(msg,)))
    pool.close()
    pool.join()
    for res in result:
        print(res)
        print(":::",res.get())
# 运行结果
msg: hello 0
msg: hello 1
msg: hello 2
end
end
end
<multiprocessing.pool.ApplyResult object at 0x0000027BF6B3F0D0>
::: donehello 0
<multiprocessing.pool.ApplyResult object at 0x0000027BF6F4FDF0>
::: donehello 1
<multiprocessing.pool.ApplyResult object at 0x0000027BF6F4FDC0>
::: donehello 2

到此这篇关于python多线程中获取函数返回值的三种方法的文章就介绍到这了,更多相关python多线程中获取函数返回值内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Python中逗号转为空格的三种方法

    Python中逗号转为空格的三种方法

    本文介绍了Python中将逗号转换为空格的三种方法,包含使用replace函数、使用split函数、使用正则表达式,具有一定的参考价值,感兴趣的可以了解一下
    2024-02-02
  • python操作cfg配置文件方式

    python操作cfg配置文件方式

    今天小编就为大家分享一篇python操作cfg配置文件方式,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2019-12-12
  • 在Python中过滤Windows文件名中的非法字符方法

    在Python中过滤Windows文件名中的非法字符方法

    今天小编就为大家分享一篇在Python中过滤Windows文件名中的非法字符方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2019-06-06
  • Ubuntu下安装PyV8

    Ubuntu下安装PyV8

    本文给大家简单介绍了下在ubuntu下安装pyv8的方法和注意事项,非常的实用,有需要的小伙伴可以参考下
    2016-03-03
  • 使用Python解析JSON数据的基本方法

    使用Python解析JSON数据的基本方法

    这篇文章主要介绍了使用Python解析JSON数据的基本方法,是Python入门学习中的基础知识,需要的朋友可以参考下
    2015-10-10
  • 下载给定网页上图片的方法

    下载给定网页上图片的方法

    这篇文章主要介绍了下载给定网页上图片的方法,需要的朋友可以参考下
    2014-02-02
  • 学python需要去培训机构吗

    学python需要去培训机构吗

    在本篇文章里小编给大家整理的是关于学python是否需要去培训机构的相关内容,有需要的朋友们可以阅读下。
    2020-07-07
  • 基于Python的接口测试框架实例

    基于Python的接口测试框架实例

    下面小编就为大家带来一篇基于Python的接口测试框架实例。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2016-11-11
  • 一文详解如何在Python中实现switch语句

    一文详解如何在Python中实现switch语句

    这篇文章主要给大家介绍了关于如何在Python中实现switch语句的相关资料,今天在学习python的过程中,发现python没有switch这个语法,所以这里给大家总结下,需要的朋友可以参考下
    2023-09-09
  • Django配置文件代码说明

    Django配置文件代码说明

    在本篇文章里小编给大家整理了关于Django配置文件代码说明知识点,有需要的朋友们学习下。
    2019-12-12

最新评论