前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python多线程,获取多线程的返回值

python多线程,获取多线程的返回值

作者头像
MachineLP
发布2018-01-09 15:43:58
3.6K0
发布2018-01-09 15:43:58
举报
文章被收录于专栏:小鹏的专栏小鹏的专栏

代码如下:

代码语言:javascript
复制
# coding=utf-8

import threading
from time import ctime, sleep

# 多线程如何返回值
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 music(func):
	for i in range(2):
		print ("I was listening to %s. %s" %(func,ctime()))
		sleep(1)

def move(func):
	for i in range(2):
		print ("I was at the %s! %s" %(func,ctime()))
		sleep(5)

def add(a, b):
	#print ('a+b:', a+b)
	return a+b

threads = []
t1 = threading.Thread(target=music, args=(u'爱情买卖',))
threads.append(t1)
t2 = threading.Thread(target=move, args=(u'阿凡达',))
threads.append(t2)

t3 = MyThread(add, args=(1,2,))
threads.append(t3)

if __name__ == '__main__':
	for t in threads[:2]:
		t.setDaemon(True)
		t.start()

	for t in threads[2:]:
		t.setDaemon(True)
		t.start()
	print ("MyThread:a+b=%d ! %s" % (t.get_result(),ctime()))

	print ("all over %s" %ctime())

输出结果:

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017年12月18日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档