• 技术文章 >Python技术 >Python基础教程

    如何使用python多线程并返回值?

    2020-11-07 14:16:16原创2512
    有小伙伴在后台给小编留言,希望出这一起关于多线程返回值的问题,于是,小编整理了很多内容,最终给大家呈现多种方式,希望大家可以在不同的场景应用时,能有不同的效果,一起来看下吧~

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

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

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

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

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

    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

    29

    30

    31

    # 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 实例并没有返回结果的方法. 需要自己实现,自己定义一个类:

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    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知识,可以到python学习网进行查询。

    专题推荐:python多线程并返回值
    上一篇:如何使用pycharm开发图形化界面? 下一篇:python真正实现多线程要怎么做?

    相关文章推荐

    • 如何使用python写自动化脚本?• python的主流开发工具有哪些?• python界面开发工具哪个好?

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网