脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - python获取多线程及子线程的返回值

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

2020-12-18 00:18Python教程网 Python

这篇文章主要介绍了python获取多线程及子线程的返回值的相关资料,需要的朋友可以参考下

最近有个需求,用多线程比较合适,但是我需要每个线程的返回值,这就需要我在threading.Thread的基础上进行封装

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import threading
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 # 如果子线程不使用join方法,此处可能会报没有self.result的错误
  except Exception:
   return None
def foo(a,b,c):
 time.sleep(1)
 print a*2,b*2,c*2,
 return a*2,b*2,c*2
st = time.time()
li = []
for i in xrange(4):
 t = MyThread(foo,args=(i,i+1,i+2))
 li.append(t)
 t.start()
for t in li:
 t.join() # 一定要join,不然主线程比子线程跑的快,会拿不到结果
 print t.get_result()
et = time.time()
print et - st

执行结果

?
1
2
3
4
5
0 2 4 (0, 2, 4)
4 6 8 2 4 6 (2, 4, 6)
(4, 6, 8)
6 8 10 (6, 8, 10)
1.00200009346

元组中的结果是函数foo的返回值,至于结果为什么这么乱,我猜,是因为各子线程foo的print和主线程print get_result()一起抢占系统资源造成。

下面介绍下python获得子线程的返回值,具体代码如下所示:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import sys
import threading
import Queue
q = Queue.Queue()
def worker1(x, y):
 func_name = sys._getframe().f_code.co_name
 print "%s run ..." % func_name
 q.put((x + y, func_name))
def worker2(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 = list()
 t1 = threading.Thread(target=worker1, name='thread1', args=(10, 5, ))
 t2 = threading.Thread(target=worker2, name='thread2', args=(20, 1, ))
 print '-' * 50
 t1.start()
 t2.start()
 t1.join()
 t2.join()
 while not q.empty():
  result.append(q.get())
 for item in result:
  if item[1] == worker1.__name__:
   print "%s 's return value is : %s" % (item[1], item[0])
  elif item[1] == worker2.__name__:
   print "%s 's return value is : %s" % (item[1], item[0])

这是目前最主流的获取线程数据的方法。使用 Queue 库创建队列实例,用来储存和传递线程间的数据。Python 的队列是线程安全的,也就是说多个线程同时访问一个队列也不会有冲突。Python 队列有三种 FIFO 先进先出,FILO 先进后出(类似栈),优先级队列(由单独的优先级参数决定顺序)。使用队列可以实现简单 生产者 – 消费者 模型

总结

以上所述是小编给大家介绍的python获取多线程及子线程的返回值,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对服务器之家网站的支持!

延伸 · 阅读

精彩推荐