线程 - 主线程永久运行,其他线程取决于另一个线程

发布于 2025-02-07 21:12:21 字数 290 浏览 2 评论 0原文

我是Python和Preading的新手。我的目标是拥有一个正在永久运行的主线程,而其他依赖另一个线程则取决于另一个线程。我使用.join()尝试了不同的事情,但是我无法得到答案。

这是我脑海中提出的图片: 线程想象

我是否需要守护程序之类的东西,或者我可以用简单的>解决此问题.join()

Im pretty new to python and threading. My goal was it to have one main thread that is running permanently and other threads that are dependent on another. I tried different things with .join() but i couldnt get an answer.

Here is a picture what ive come up with in my mind:
Thread Imagination

Do i need something like a daemon or can i solve this with just simple .join()?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

剑心龙吟 2025-02-14 21:12:21

尝试该结构:

from threading import Thread
from time import sleep

def do_work_1():
    print("Thread 1 starting")
    sleep(1)
    print("Thread 1 done")

def do_work_2(parent_thread):
    print("Thread 2 wait thread 1 to finish")
    parent_thread.join()
    print("Thread 2 starting")
    sleep(1)
    print("Thread 2 done")

def do_work_3(parent_thread):
    print("Thread 3 wait thread 2 to finish")
    parent_thread.join()
    print("Thread 3 starting")
    sleep(1)
    print("Thread 3 done")

thread1 = Thread(target=do_work_1)
thread2 = Thread(target=do_work_2, args=(thread1,)) # Do not miss the comma!
thread3 = Thread(target=do_work_3, args=(thread2,))

thread1.start()
thread2.start()
thread3.start()

for num in range(6):
    print("Main thread still do job", num)
    sleep(0.60)

thread3.join()
print("Job done")

Try that structure:

from threading import Thread
from time import sleep

def do_work_1():
    print("Thread 1 starting")
    sleep(1)
    print("Thread 1 done")

def do_work_2(parent_thread):
    print("Thread 2 wait thread 1 to finish")
    parent_thread.join()
    print("Thread 2 starting")
    sleep(1)
    print("Thread 2 done")

def do_work_3(parent_thread):
    print("Thread 3 wait thread 2 to finish")
    parent_thread.join()
    print("Thread 3 starting")
    sleep(1)
    print("Thread 3 done")

thread1 = Thread(target=do_work_1)
thread2 = Thread(target=do_work_2, args=(thread1,)) # Do not miss the comma!
thread3 = Thread(target=do_work_3, args=(thread2,))

thread1.start()
thread2.start()
thread3.start()

for num in range(6):
    print("Main thread still do job", num)
    sleep(0.60)

thread3.join()
print("Job done")

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文