Pythonでマルチスレッド再び

以前、Pythonでマルチスレッド処理を行うプログラムを書いた。そのときはthreading.ThreadとQueue.Queueを使っていた。それはPython2.7を使っていたから。
しかし、今はPython3がメインだ。concurrent.futures.ThreadPoolExecutorを使えばもっとスマートに実装できる。

Python3

from concurrent.futures import ThreadPoolExecutor

def download(name, url):
    pass

target_url_list = []  # URL List
tp = ThreadPoolExecutor(max_workers=4)
for url in target_url_list:
    tp.submit(download, url.name, url.url)
tp.shutdown()
print('End')

とても簡単に書くことができる。max_workersに応じて多重度を調整してくれる。ThreadPoolExecutorのshutdown()メソッドで、すべてのスレッドの終了を待ち合わせてくれる。
これは便利。

Python2(参考)

import threading
import Queue

def download(q):
    while True:
        item = q.get()
        if item is None:
            break
        name = item.name
        url = item.url
        pass

target_url_list = []  # URL List
q = Queue.Queue()

thread_list = []
for i in range(4):
    thread = threading.Thread(target=download, args=(q,))
    thread.start()
    thread_list.append(thread)

for item in target_url_list:
    q.put(item)

for i in range(len(thread_list)):
    q.put(None)

for thread in thread_list):
    thread.join()

print('End')

以前はこれが普通だったけれど、今見るととても冗長だ。

まとめ

もうPython2のことは忘れてPython3でどんどん作ろう。
(はやくJythonがPython3系になってくれると良いのだが・・・)

同じタグの記事
同じカテゴリの記事

コメントを残す

メールアドレスが公開されることはありません。

CAPTCHA