重庆分公司,新征程启航

为企业提供网站建设、域名注册、服务器等服务

使用python多线程并返回值的方法

这篇文章主要介绍了使用python多线程并返回值的方法,具有一定借鉴价值,需要的朋友可以参考下。希望大家阅读完这篇文章后大有收获。下面让小编带着大家一起了解一下。

创新互联主营封丘网站建设的网络公司,主营网站建设方案,APP应用开发,封丘h5微信平台小程序开发搭建,封丘网站营销推广欢迎封丘等地区企业咨询

Python 从多线程中返回值,有多种方法:

1、常见的有写一个自己的多线程类,写一个方法返回。

2、可以设置一个全局的队列返回值。

3、也可以用multiprocessing.pool.ThreadPool 。

下面写一个类从线程中返回值

# coding:utf-8
import time
 
from threading import Thread
 
def foo(number):
    time.sleep(20)
    return number
 
class MyThread(Thread):
 
    def __init__(self, number):
        Thread.__init__(self)
        self.number = number
 
    def run(self):
        self.result = foo(self.number)
 
    def get_result(self):
        return self.result
 
 
thd1 = MyThread(3)
thd2 = MyThread(5)
thd1.start()
thd2.start()
thd1.join()
thd2.join()
 
print thd1.get_result()
print thd2.get_result()

另外,自带的Thread 实例并没有返回结果的方法. 需要自己实现,自己定义一个类:

class CustomTask:
    def __init__(self):
        self._result = None
    
    def run(self, *args, **kwargs):
        # 你的代码, 你用来进行多线程
        result = ...
        self._result = result
    
    def get_result(self):
        return self._result
这里自己实现了 `get_result` 方法。
使用
import threading
 
ct = CustomTask()
t = threading.Thread(target=ct.run, args=(...))
t.start()
# 结束之后
result = ct.get_result()

感谢你能够认真阅读完这篇文章,希望小编分享使用python多线程并返回值的方法内容对大家有帮助,同时也希望大家多多支持创新互联,关注创新互联行业资讯频道,遇到问题就找创新互联,详细的解决方法等着你来学习!


网站名称:使用python多线程并返回值的方法
URL地址:http://cqcxhl.com/article/ipogjs.html

其他资讯

在线咨询
服务热线
服务热线:028-86922220
TOP