本网站(662p.com)打包出售,且带程序代码数据,662p.com域名,程序内核采用TP框架开发,需要联系扣扣:2360248666 /wx:lianweikj
精品域名一口价出售:1y1m.com(350元) ,6b7b.com(400元) , 5k5j.com(380元) , yayj.com(1800元), jiongzhun.com(1000元) , niuzen.com(2800元) , zennei.com(5000元)
需要联系扣扣:2360248666 /wx:lianweikj
python多线程中获取函数返回值的三种方法
飘飘悠悠 · 152浏览 · 发布于2023-03-02 +关注

本文主要介绍了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


相关推荐

PHP实现部分字符隐藏

沙雕mars · 1325浏览 · 2019-04-28 09:47:56
Java中ArrayList和LinkedList区别

kenrry1992 · 908浏览 · 2019-05-08 21:14:54
Tomcat 下载及安装配置

manongba · 970浏览 · 2019-05-13 21:03:56
JAVA变量介绍

manongba · 963浏览 · 2019-05-13 21:05:52
什么是SpringBoot

iamitnan · 1087浏览 · 2019-05-14 22:20:36
加载中

0评论

评论
分类专栏
小鸟云服务器
扫码进入手机网页