0
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?

More than 3 years have passed since last update.

カレーライス作りで学ぶマルチスレッド

0
Last updated at Posted at 2021-10-16

threadingというものがいまいちよくわかってなかったのですが、カレーライスのたとえ話ですんなり理解できたので共有したいと思います。

たとえばカレーライスを作るのに、カレーに20分、ご飯に40分かかるとします。

ご飯を作ったあとでカレーを作ると 20+40=60分 かかります
同時に作リ始めれば 40分 で済みます。
後者を実現するのにthreadingを使います。

curry.png

test.py
import time
import datetime

ctime = 2    # カレーにかかる時間
rtime = 4    # ご飯にかかる時間

def rice():
  print('  ご飯を炊きます')
  time.sleep(rtime)
  print('  ご飯ができました。')

def curry():
  print('  カレーをつくります。')
  time.sleep(ctime)
  print('  カレーができました。')

def tikuji():  # 逐次
    rice()
    curry()
    print('カレーライスのできあがり')

def doji():  # 同時
    import threading
    thread1 = threading.Thread(target=rice)  # インスタンス作成
    thread2 = threading.Thread(target=curry)
    thread1.start()  # 開始
    thread2.start()
    thread1.join()  # 終了を待つ文
    thread2.join()
    print('カレーライスのできあがり')

a = input("1:逐次 2:同時")
# 時間計測
st = datetime.datetime.today()
print(st)
if a == "1":
    tikuji() 
else:   
    doji()   
et = datetime.datetime.today()
de = et - st

print("かかった時間は", de)

thread1.join()の部分が終了を待つ文です。
これがないとご飯ができないにも関わらず'カレーライスのできあがり'と表示されてしまいます。

repl.itで試せます

0
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
0
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?