【问题标题】:Python How to start Thread inside another one?Python 如何在另一个线程中启动线程?
【发布时间】:2019-01-03 18:33:09
【问题描述】:

我正在尝试启动多个线程,下一个线程的启动时间将取决于它会在第一个等中发生的情况。

所以我在 Stackoverflow 中找到了一些类似这样的帖子,在他谈到 Event 类的答案中: Python threading - How to repeatedly execute a function in a separate thread?

所以我尝试这样做:

from threading import Thread, Event
import time

class MyThread3(Thread):
    def __init__(self, event):
        Thread.__init__(self)
        self.stopped = event

    def run(self):
        while self.stopped.wait(0.5):
            print("The Third thread is running..")


class MyThread2(Thread):
    def __init__(self, event):
        Thread.__init__(self)
        self.stopped = event

    def run(self):
        time.sleep(1)
        my_event2.clear()
        time.sleep(3)
        my_event.set()
        time.sleep(2)
        my_event2.set()

class MyThread1(Thread):
    def __init__(self, event):
        Thread.__init__(self)
        self.stopped = event

    def run(self):
        while not self.stopped.wait(0.5):
            print("Thread is running..")

my_event = Event()
my_event2 = Event()
thread1 = MyThread1(my_event)
thread2 = MyThread2(my_event)
thread3 = MyThread3(my_event2)
thread1.start()
thread2.start()
thread3.start()

thread1.join()
thread2.join()
thread3.join()

如果我不在 Thread3 中时它会与 Thread1 同时启动,那么为什么如果我放置了相反的位置并且事件的状态发生了变化并且它没有启动呢? 我们不能更改线程内的事件? 如何从另一个线程启动一个线程?

【问题讨论】:

  • “启动线程”是什么意思?通常的意思是.start 方法启动线程。另请注意,您对线程 3 使用私有 my_event2,(其他两个线程都使用 my_event)。所以你几乎无法控制其他线程的thread3执行。

标签: multithreading events


【解决方案1】:

嗯,你说得对,我什至没想到。

我找到了解决方案:

import time
from threading import Thread, Event

class MyThread1(Thread):
    def __init__(self, event):
        Thread.__init__(self)
        self.stopped = event

    def run(self):
        x = 0
        while not self.stopped.wait(0.5):
            if x == 5:
                    thread2.start()
            print("Thread 1 is running..")
            x += 1


class MyThread2(Thread):
    def __init__(self):
        Thread.__init__(self)

    def run(self):
        print("Procces 2 start and the process 1 will stop in 2 seconds")
        x = 0
        while x < 10:
            if x == 5:
                my_event.set()
            print("x = ",x)
            time.sleep(0.5)
            x += 1

my_event = Event()
thread1 = MyThread1(my_event)
thread2 = MyThread2()

thread1.start()

我发现的解决方案似乎不是很好,还有什么其他建议可以编写干净的代码吗?

我还有一个关于这种多线程的问题,我们如何在一个线程中使用一个变量来在另一个线程中使用它?

例如:

线程 1 正在运行 线程 2 正在运行

线程 1 正在等待 10 分钟,并将检查变量 Default 线程 2 计算一些东西并将变量 Default 更改为 20

线程1等待10分钟后,看到Default的值为20,做一个任务,如果不是就结束。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-19
    • 2013-04-21
    相关资源
    最近更新 更多