LoginSignup
0
2

More than 3 years have passed since last update.

【Python】threadingによる並列処理

Last updated at Posted at 2021-03-02

使い方は簡単

import threading

def thread1():
    '''
    別のスレッドとして実行させたい内容
    '''

if __name__ == '__main__':

    # スレッドthの作成.targetで行いたいメソッド,nameでスレッドの名前,argsで引数を指定する
    th = threading.Thread(target=thread1,name="th",args=())

    # thをデーモンに設定する.メインスレッドが終了するとデーモンスレッドも一緒に終了する
    th.setDaemon(True)
    th.start()

    '''
    実行させたい内容
    '''

(例)1から100までカウント.qが入力されたら強制終了.

#coding:utf-8

import threading
import sys
from time import sleep

class Config:
    fg = False

def thread1():
    while True:    
        c = sys.stdin.read(1)
        if c == 'q':
            Config.fg = True

if __name__ == '__main__':
    th = threading.Thread(target=thread1,name="th",args=())
    th.setDaemon(True)
    th.start()

    for i in range(1,101):
        if Config.fg:
            sys.exit()
        print(i)
        sleep(1)

実行結果
(a->b->c->qの順に入力)

python3 thread.py 
1
2
3
4
5
6
a
7
8
b
9
c
10
11
q
0
2
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
0
2