Help us understand the problem. What is going on with this article?

pythonでマルチスレッドで処理して各スレッドの結果を受け取る

More than 1 year has passed since last update.

やりたいこと

pythonでマルチスレッド処理を行う

コード

threadingという標準モジュールを利用してできるみたいなので試してみる
python2とpython3両方とも同じように利用できるみたいで便利!

#!/usr/bin/env python

import threading
import time

__author__ = "oomori"
__version__ = "1.0.0"

def myfunc(test_arg, results):
    """
    This is a test function of multithreading
    :param test_arg
    :return: None
    """
    print("call target_func")
    print("thread name is %s" % threading.current_thread().name)
    print(test_arg)
    output = test_arg * 2
    print("output is %d" % output)
    results[threading.current_thread().name] = output

def main():
    """
    main
    :return: None
    """

    results = dict()
    for _  in range(0, 10):
        threadlist = list()
        for thread_num in range(0, 5):
            thread = threading.Thread(target=myfunc, args=([thread_num, results]),-
                    name="thread%d" % thread_num)
            threadlist.append(thread)

        for thread in threadlist:
            thread.start()

        for thread in threadlist:
            thread.join()

        print("=== show each thread results ===")
        for k in results:
            print(k, results[k])
        time.sleep(5)

if __name__ == "__main__":
    main()  

thread=の部分でターゲットとなる関数とその引数、
さらにそのスレッドの名前を定義しています。
スレッドの名前は定義しない場合、"Thread-1"というようにつけられるそうです。

いったんthreadlistに格納してから、startさせている理由は、
ほぼ同時に目的となる関数を実行させたいためです。
(リクエストをほぼ同時に投げるなど)

また、thread.join()で各スレッドが終了するまで待機することで、
resultsに全てのスレッドの結果が格納されます。

出力はこんな感じになります。

call target_func
thread name is thread0
0
output is 0
call target_func
thread name is thread1
1
output is 2
call target_func
thread name is thread2
2
output is 4
call target_func
thread name is thread3
3
output is 6
call target_func
thread name is thread4
4
output is 8
=== show each thread results ===
thread0 0
thread1 2
thread2 4
thread3 6
thread4 8


call target_func
thread name is thread0
0
output is 0
call target_func
thread name is thread1
1
output is 2
call target_func
thread name is thread2
2
output is 4
call target_func
thread name is thread3
3
output is 6
call target_func
thread name is thread4
4
output is 8
=== show each thread results ===
thread0 0
thread1 2
thread2 4
thread3 6
thread4 8

...

まだまだ使い方とか注意点等いろいろあるとは思いますが、
とりあえず、自分がやりたいことはできたので、よしとしよう

参考

komorin0521
1989年(平成)生まれの 好きな言語: Python フォローされてない方からのコメントも大歓迎です! なお、投稿した記事は個人としてのものであり、所属する団体とは関係ございません。
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした