LoginSignup
38
49

More than 5 years have passed since last update.

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

Last updated at Posted at 2017-11-16

やりたいこと

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

...

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

参考

38
49
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
38
49