python获取多线程线程执行结果

python的threading模块有提供多线程的执行方法,在计算密集型操作里也用不上,很多时候是在处理IO密集型的操作里使用,能为我们节省不少时间,但他本身不提供获取线程执行结果,需要我们自行实现,目前最简单的办法就是使用Queue来实现,Queue在线程之间是共享的,并且本身就提供了良好的加锁机制,可以直接使用。

首先简单封装下threading模块,取名为mythreading.py:

# coding=utf-8
# python2适用 python3可能略有不同,请自行修改

import threading

class MyMutiThread():
    def __init__(self):
        self.runlist = list()

    def muti_thread_add(self, func, name, *args, **kwargs):
        t = threading.Thread(target=func, name=name, args=args, kwargs=kwargs)
        self.runlist.append(t)

    def muti_thread_start(self):
        for t in self.runlist:
            t.start()

    def muti_thread_wait(self):
        for t in self.runlist:
            t.join()

接下来具体实现多线程的方法:

# coding=utf-8

import Queue
import mythreading

def my_function(arg1):
    '''你的操作'''
    time.sleep(1)  #模拟你的操作
    result = "执行结果"
    result_q.put(result)

if __name__ == '__main__':
    # 开始处理并发
    result_q = Queue.Queue()   # 创建队列记录线程执行结果
    test_muti_thread = mythreading.MyMutiThread()
    test_muti_thread.muti_thread_add(my_function, "my_thread_name1", "arg1", result_q)
    test_muti_thread.muti_thread_add(my_function, "my_thread_name2", "arg2", result_q)
    test_muti_thread.muti_thread_start()
    test_muti_thread.muti_thread_wait()   # 等待执行完成
    result = list()
    while not result_q.empty():   # 校验执行结果
        result.append(result_q.get())
    print(result)   #获得结果
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 线程 操作系统线程理论 线程概念的引入背景 进程 之前我们已经了解了操作系统中进程的概念,程序并不能单独运行,只有...
    go以恒阅读 1,692评论 0 6
  • 1.ios高性能编程 (1).内层 最小的内层平均值和峰值(2).耗电量 高效的算法和数据结构(3).初始化时...
    欧辰_OSR阅读 29,671评论 8 265
  • 引言&动机 考虑一下这个场景,我们有10000条数据需要处理,处理每条数据需要花费1秒,但读取数据只需要0.1秒,...
    chen_000阅读 529评论 0 0
  • 那个7月,于我而言是不一样的。毕业以后,工作没有着落的我瞬间成了待业青年。 因为一直执著于自己的喜好...
    庄酱和夏桑阅读 356评论 0 4
  • 文|余语于隅 砍竹深篁里,匠心而营作。 小筏已初成,邀请送入河。 一竿荡开去,两岸青山阔。 中内无忧愁,烦恼丝尽落。
    余语于隅阅读 395评论 0 8