python多线程中获取函数返回值的方法有哪些

其他教程   发布日期:2023年07月21日   浏览次数:528

这篇文章主要介绍“python多线程中获取函数返回值的方法有哪些”,在日常操作中,相信很多人在python多线程中获取函数返回值的方法有哪些问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”python多线程中获取函数返回值的方法有哪些”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

方法一:使用队列

  1. import queue
  2. import threading
  3. import sys
  4. import time
  5. q=queue.Queue()
  6. def func1(x,y):
  7. func_name = sys._getframe().f_code.co_name # 获取函数名
  8. print("%s run ....." % func_name)
  9. q.put((x+y,func_name))
  10. def func2(x,y):
  11. func_name = sys._getframe().f_code.co_name
  12. print("%s run ...." %func_name)
  13. q.put((x-y,func_name))
  14. if __name__ == "__main__":
  15. result=[]
  16. t1=threading.Thread(target=func1,name="thread1",args=(10,5))
  17. t2=threading.Thread(target=func2,name="thread2",args=(20,1))
  18. print('*'*20)
  19. t1.start()
  20. t2.start()
  21. t1.join()
  22. t2.join()
  23. while not q.empty():# 队列为空返回True,反之False
  24. result.append(q.get())
  25. for item in result:
  26. if item[1] == func1.__name__:
  27. print("%s return value is: %s" %(item[1],item[0]))
  28. elif item[1] == func2.__name__:
  29. 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 方法

  1. class mythread(threading.Thread):
  2. def __init__(self,func,args=()):
  3. super(mythread, self).__init__()
  4. self.func=func
  5. self.args=args
  6. def run(self):
  7. self.result=self.func(*self.args)
  8. def get_result(self):
  9. try:
  10. return self.result
  11. except Exception:
  12. return None
  13. def foo(a,b,c):
  14. time.sleep(1)
  15. return a*2,b*2,c*2
  16. li = []
  17. for i in range(4):
  18. t=mythread(foo,args=(i,i+1,i+2))
  19. li.append(t)
  20. t.start()
  21. for t in li:
  22. t.join()
  23. print(t.get_result())
  24. # 运行结果
  25. (0, 2, 4)
  26. (2, 4, 6)
  27. (4, 6, 8)
  28. (6, 8, 10)

方法三:使用进程池

  1. def func(msg):
  2. print("msg:",msg)
  3. time.sleep(3)
  4. print("end")
  5. return "done" + msg
  6. if __name__ == "__main__":
  7. pool = multiprocessing.Pool(processes=4)
  8. result = []
  9. for i in range(3):
  10. msg = "hello %d" %i
  11. result.append(pool.apply_async(func,(msg,)))
  12. pool.close()
  13. pool.join()
  14. for res in result:
  15. print(res)
  16. print(":::",res.get())
  17. # 运行结果
  18. msg: hello 0
  19. msg: hello 1
  20. msg: hello 2
  21. end
  22. end
  23. end
  24. <multiprocessing.pool.ApplyResult object at 0x0000027BF6B3F0D0>
  25. ::: donehello 0
  26. <multiprocessing.pool.ApplyResult object at 0x0000027BF6F4FDF0>
  27. ::: donehello 1
  28. <multiprocessing.pool.ApplyResult object at 0x0000027BF6F4FDC0>
  29. ::: donehello 2

以上就是python多线程中获取函数返回值的方法有哪些的详细内容,更多关于python多线程中获取函数返回值的方法有哪些的资料请关注九品源码其它相关文章!