python 线程池的坑及本身实现简化线程池

    在一个项目中想要使用线程池,而后当时的方向是muliprocess 的threadpool ,网上还搜到一个threadoool。 当时心血来潮,看了网上一个例子就使用了threadpool, 连接以下https://pypi.python.org/pypi/threadpool/,而后被坑了,这个库是有严重问题的,不是线程安全的。而后一气之下,项目中的直接使用本身实现的简化线程池。python

该文章后续仍在不断的更新修改中, 请移步到原文地址http://dmwan.cc安全

    大体原理是,一个传入参数list, 一个返回结果list,每一个thread pop from the list ,由于当list 为空的时候,会报异常,咱们捕捉这个异常,当成线程退出的信号。同时,将结果都append 到返回结果的list,这样就达到了一个最简版线程池的目的。而后性能吧,必定比官方版本要快!数据结构

    代码实例以下:    app

in_list = []
out_list = []

# 启动THREAD_NUM 个线程, 传入参数list 和 回收结果list

for item in range(THREAD_NUM):
    threads.append(threading.Thread(target=thread_dedect, args=(item, in_list, out_list))

    for t in threads:
        t.start()

    for t in threads:
        t.join()

# 处理输出list
do(out_list)


def thread_dedect(in_list, out_list):
    while True:
        try:
            data = in_list.pop()
        except Exception: # 这里异常粒度能够细分
            logger.debug("the thread %s has exited" % item)
            return
        
        res = do(data)
        out_list.append(res)

    这里利用的是list 是线程安全的数据结构和list 自己的特性。性能

    和官方的multiprocess 的用法基本一致,可是好处在于省去了中间的序列化过程。线程

    有时间,加下性能对比。debug

相关文章
相关标签/搜索