LoginSignup
19
21

More than 5 years have passed since last update.

Python スレッドの停止と再開の簡易サンプル

Last updated at Posted at 2019-06-21

はじめに

pythonで処理を並列に行いたいと思いました
しかし、マルチスレッドに関する知識がありませんでした。
そこでとりあえず動くレベルで良いので勉強してみました。
ざっくりとしたものですが、記事に残してみようと思います。

Python 3.7.3で動作確認しました。

要件

  1. マルチスレッドで処理を並行で行いたい。
  2. スレッドの処理を頻繁に停止・再開をしたい

実装

メンバにスレッドを持つタイプ

python
import threading
import time

class Test1():
  def __init__(self):
    self.started = threading.Event()
    self.alive = True
    self.thread = threading.Thread(target=self.func)
    self.thread.start()

  def __del__(self):
    self.kill()

  def begin(self):
    print("begin")
    self.started.set()

  def end(self):
    self.started.clear()
    print("\nend")

  def kill(self):
    self.started.set()
    self.alive = False
    self.thread.join()

  def func(self):
    i = 0
    self.started.wait()
    while self.alive:
      i += 1
      print("{}\r".format(i), end="")
      self.started.wait()

test = Test1()
test.begin()
time.sleep(2)
test.end()
test.begin()
time.sleep(2)
test.end()
test.begin()
time.sleep(2)
test.end()
test.kill()

threading.Threadを継承するタイプ

class Test2(threading.Thread):
  def __init__(self):
    super().__init__()
    self.started = threading.Event()
    self.alive = True
    self.start()

  def __del__(self):
    self.kill()

  def begin(self):
    print("begin")
    self.started.set()

  def end(self):
    self.started.clear()
    print("\nend")

  def kill(self):
    self.started.set()
    self.alive = False
    self.join()

  def run(self):
    i = 0
    self.started.wait()
    while self.alive:
      i += 1
      print("{}\r".format(i), end="")
      self.started.wait()

test = Test2()
test.begin()
time.sleep(2)
test.end()
test.begin()
time.sleep(2)
test.end()
test.begin()
time.sleep(2)
test.end()
test.kill()

最後に

ざっくりとした記事と書いた割には、大分トリッキーな気もしますが

19
21
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
19
21