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 1 year has passed since last update.

Python 単一スレッド内で複数のスレッドを立ち上げてイベント制御したいときに読む (15秒で読めます)

Last updated at Posted at 2022-03-17
from threading import Thread, Event
import time
import random


class MyEvent():
    th1 = Event()
    th2 = Event()


def task1(event: MyEvent):
    while True:
        event.th1.wait()
        print('th1 run.')
        event.th1.clear()


def task2(event: MyEvent):
    while True:
        event.th2.wait()
        print('th2 run.')
        event.th2.clear()


# manage_thがth1とth2を立ち上げる
def manage_th(event: MyEvent):
    task_list = [task1, task2]
    for task in task_list:
        th = Thread(target=task, args=(event,), daemon=True)
        th.start()
    while True:
        # th1とth2のイベント制御を行う
        # n秒後にth1をsetして,n秒後にth2をsetする
        time.sleep(random.random())
        event.th1.set()
        time.sleep(random.random())
        event.th2.set()


# メインスレッド
def main_thread():
    while True:
        time.sleep(5)
        break


event = MyEvent()
th = Thread(target=manage_th, args=(event,), daemon=True)
th.start()

# 5秒後にメインスレッドを終了 → manage_th終了 → th1,th2終了
main_thread()

感想

そろそろスレッド制御脱初心者したいですね。

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?