0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

マルチスレッド

Last updated at Posted at 2024-11-11

はじめに

マルチスレッドを書いてみました。threading.Thread(target=self._run_timer).start() の部分が大切です。

timer_counter
import threading
import time

class TimerCounter:
    def __init__(self):
        self.seconds_count = 0
        self.running = True
        threading.Thread(target=self._run_timer).start()

    def _run_timer(self):
        # 1 秒ごとにカウントを増やすのじゃ
        while self.running:
            time.sleep(1)
            self.seconds_count += 1

    def get_seconds(self):
        # 現在の経過秒数を返すのじゃ
        return self.seconds_count

    def __del__(self):
        # タイマーを停止するのじゃ
        self.running = False
main.py
from timer_counter import TimerCounter

# インスタンスを作成して使う部分
timer_counter = TimerCounter()

try:
    while True:
        input("エンターを押すと経過時間を表示するのじゃ(終了するにはCtrl+Cを押すのじゃ)...")
        print(f"経過時間: {timer_counter.get_seconds()}")
except KeyboardInterrupt:
    print("プログラムを終了するのじゃ")
    del timer_counter  # インスタンス削除でタイマーを停止

この二つを同じフォルダにおいて、main.py を実行すれば動きます。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?