获取Python多线程的返回值

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012050154/article/details/80032072

用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

猜你喜欢

转载自blog.csdn.net/u012050154/article/details/80032072