1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Python】マルチスレッド その1 threadingの利用

Posted at

背景

pythonでマルチスレッドが必要になり、使用方法について調査してみました。threadingモジュールを使用するのが一般的なようです。

環境

  • Macbook Air M1
  • macOS Sonoma 14.0
  • python 3.11

コード

ログに各スレッド名を出力するようにしました。

main.py
import threading
import time

# Log
def log(str):
    print("[{}] {}".format(threading.current_thread().name, str ))
    
# Sub 
def worker():
    log('Invoked')
    time.sleep(3)
    log('Completed')

# Main
if __name__=="__main__":
    log('Start')

    log('Invoking worker...')
    worker_thread = threading.Thread(target = worker, name = 'workder thread', daemon = True)
    worker_thread.start()
    worker_thread.join()

    # 後処理
    log('End')



実行結果

% python3 main.py
[MainThread] Start
[MainThread] Invoking worker...
[workder thread] Invoked
[workder thread] Completed
[MainThread] End
1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?