11
18

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Pythonでのマルチスレッド処理

Posted at

マルチスレッド処理とは

  • 特定の操作をスレッドに分割し、各スレッドにて並行で処理を実行させる

マルチスレッド処理をしないと

  • 例えばこのようなコード
# -*- coding: utf-8 -*-
import time

def myfunc(i):
   
    time.sleep(10)
    print("execute:" + str(i))

def main():
    
    for i in range(10):
        print("call myfunc:" + str(i))
        myfunc(i)
     
if __name__ == "__main__":
    main()  
  • myfuncは時間がかかる関数を想定しているのでsleepを入れています
  • 実行結果は以下の通り
call myfunc:0
execute:0
call myfunc:1
execute:1
call myfunc:2
execute:2
call myfunc:3
execute:3
call myfunc:4
execute:4
call myfunc:5
execute:5
call myfunc:6
execute:6
call myfunc:7
execute:7
call myfunc:8
execute:8
call myfunc:9
execute:9
  • 目標はmyfuncの終了を待たずして次々にmyfuncの実行を行うこと

実装

threadingモジュール

  • Thread オブジェクトを使用する

Threadの代表的な引数

  • target
    • 実行する関数名を指定
  • name
    • スレッドに付与する名前
  • args
    • targetで指定した関数に渡す引数タプル

コード

  • mainのfor文内を下記のように変更
 for i  in range(10):        
        
        thread = threading.Thread(target=myfunc, args=([i]))
        thread.start()

実行結果は下記の通り

call myfunc:0
call myfunc:1
call myfunc:2
call myfunc:3
call myfunc:4
call myfunc:5
call myfunc:6
call myfunc:7
call myfunc:8
call myfunc:9

execute:0
execute:5
execute:8
execute:3
execute:6
execute:4
execute:7
execute:2
execute:1
execute:9
  • executeの出力が同時に行われます
11
18
0

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
11
18

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?