在一個項目中想要使用線程池,而後當時的方向是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