python threading 多线程模块并发,如何使用?

前言

最近工作上需要用到多线程,并且要获取多线程的返回值,python多线程一般使用threading模块,但threading模块有个问题,无法返回线程里面运行的结果。

通过查找资料,我通过如下方法来获取多线程的返回值。

 

方式1:用类的方式改写thread 来实现

from threading import Thread
def foo_a(*args): print("a的参数==>", args) return "我是函数a"

def foo_b(): return "我是函数b" def foo_c(): return "我是函数c" class MyThread(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) # 在执行函数的同时,把结果赋值给result, # 然后通过get_result函数获取返回的结果 def get_result(self): try: return self.result except Exception as e: return None if __name__ == '__main__': thd1 = MyThread(foo_a, args=(3, 4, 6)) thd2 = MyThread(foo_b, ) thd3 = MyThread(foo_c, ) thd1.start() thd2.start() thd3.start() thd1.join() thd2.join() thd3.join() print(thd1.get_result()) print(thd2.get_result()) print(thd3.get_result())

 方式2用队列queue来实现

import threading
import queue
import time

def foo_a(q,*args):
    print("a的参数==>", args)
    time.sleep(1)
    return q.put(args)

def foo_b(q):
    return q.put("我是函数b")

def foo_c(q):
    return q.put("我是函数c")

def multithreading():
    q = queue.Queue()
    threads = []
    results = []
    t1 = threading.Thread(target=foo_a, args=(q,1,3,9,))
    t2 = threading.Thread(target=foo_b, args=(q,) )
    t3 = threading.Thread(target=foo_c, args=(q,))
    t1.start()
    t2.start()
    t3.start()
    threads.append(t1)
    threads.append(t2)
    threads.append(t3)
    for thread in threads:
        thread.join()  # 等待子线程结束后,再往后面执行
    for _ in range(3):
        results.append(q.get())
    print(results)

if __name__ == '__main__':
    multithreading()

 

 

总结:

方式2 不能按照顺序来执行a,b,c函数。若是对顺序有要求考虑方式1

 

参考资料:

https://www.cxyzjd.com/article/qq_20663229/94484526

posted @ 2022-10-24 14:43  o蹲蹲o  阅读(88)  评论(0编辑  收藏  举报