获取Python多线程的返回值

本文介绍了Python中使用多线程的两种方法:方法包装线程和类包装线程。通过具体示例展示了如何创建和启动线程,以及如何获取线程的返回值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

用python多线程时,遇到需要获取每个线程返回值的问题,经查资料学习总结如下:

Python中使用线程有两种方式:用方法包装线程和用类包装线程

方法一、用方法包装线程

thread.start_new_thread ( function, args[, kwargs] )

-function 表示线程需要执行的函数

-args 表示传入的参数

# coding:utf-8

import thread, time

# 为线程定义一个函数
def print_time(threadName, delay):
    count = 0
    while count < 5:
        time.sleep(delay)
        count += 1
        print "%s: %s" % (threadName, time.ctime(time.time()))


# 创建两个线程
try:
    thread.start_new_thread(print_time, ("Thread-1", 2,))
    thread.start_new_thread(print_time, ("Thread-2", 3,))
except:
    print "Error: unable to start thread"

while 1:
    pass

运行结果如下:

Thread-1: Sat Apr 21 18:28:51 2018
Thread-2: Sat Apr 21 18:28:52 2018
Thread-1: Sat Apr 21 18:28:53 2018
Thread-2: Sat Apr 21 18:28:55 2018
Thread-1: Sat Apr 21 18:28:55 2018
Thread-1: Sat Apr 21 18:28:57 2018
Thread-2: Sat Apr 21 18:28:58 2018
Thread-1: Sat Apr 21 18:28:59 2018
Thread-2: Sat Apr 21 18:29:01 2018
Thread-2: Sat Apr 21 18:29:04 2018

方法二、用类包装线程

一个小Demo如下,MyThread.py是线程类,Main.py中有一个加法add()方法,实例中将add()方法和参数传递给多线程类处理,并通过线程的get_result()方法获取执行的结果。

# coding:utf-8

import threading, time

# MyThread.py线程类
class MyThread(threading.Thread):
    def __init__(self, func, args=()):
        super(MyThread, self).__init__()
        self.func = func
        self.args = args

    def run(self):
        time.sleep(2)
        self.result = self.func(*self.args)

    def get_result(self):
        threading.Thread.join(self) # 等待线程执行完毕
        try:
            return self.result
        except Exception:
            return None
# coding:utf-8
import ThreadClass

# main.py
def add (a, b):
    return a + b

if __name__=="__main__":
    list = [23, 89]
    # 创建4个线程
    for i in xrange(4):
        task = ThreadClass.MyThread(add, (list[0], list[1]))
        task.start()
        print(task.get_result())

运行结果:

112
112
112
112

参考资料:

1、http://www.runoob.com/python/python-multithreading.html

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值