对于守护进程daemon , join 的使用条件
daemon属性
- daemon 属性:
- 在创建线程时,可以设置线程的
daemon
属性。如果将一个线程设置为守护线程(daemon=True
),则该线程会在主线程结束时自动退出,而不管该守护线程是否完成。 - 守护线程的作用是在主线程运行时,守护线程也在运行,但主线程结束后,守护线程将被强制退出,不等待它完成。这通常用于执行一些后台任务,如监控或定期清理。
import threading import time def daemon_thread(): while True: print("Daemon thread is running...") time.sleep(1) daemon_thread = threading.Thread(target=daemon_thread) daemon_thread.daemon = True # 设置为守护线程 daemon_thread.start() time.sleep(3) # 主线程等待3秒 print("Main thread is exiting.")
join
方法用于等待线程结束。调用线程的join
方法会阻塞当前线程,直到被调用的线程执行完成。- 如果不调用
join
,主线程可能在子线程执行完之前就退出。join
用于确保主线程等待所有子线程完成,然后再继续执行。
import threading import time def worker(): time.sleep(2) print("Worker thread is done.") thread = threading.Thread(target=worker) thread.start() thread.join() # 等待子线程执行完成 print("Main thread is exiting.")
所以,daemon
和 join
的区别在于:
daemon
控制线程是否在主线程退出时自动退出。join
控制主线程是否等待子线程完成后再继续执行。
- 等待子线程完成: 当主线程启动了多个子线程,并且主线程需要等待所有子线程都执行完成后再继续执行,就可以使用
join
方法。
pythonCopy code import threading import time def worker(name, delay): print(f"{name} starts working.") time.sleep(delay) print(f"{name} finishes working.") thread1 = threading.Thread(target=worker, args=("Thread 1", 3)) thread2 = threading.Thread(target=worker, args=("Thread 2", 5)) thread1.start() thread2.start() thread1.join() thread2.join() print("All threads have finished. Main thread exits.")
- 线程协同: 在某些情况下,主线程可能需要等待一个子线程执行完成后,将结果传递给另一个子线程。通过
join
,可以确保线程的执行顺序。
pythonCopy code import threading import time result = None def worker1(): global result print("Worker 1 starts working.") time.sleep(3) result = "Result from Worker 1" print("Worker 1 finishes working.") def worker2(): global result print("Worker 2 starts working.") while result is None: time.sleep(1) print(f"Worker 2 uses result: {result}") print("Worker 2 finishes working.") thread1 = threading.Thread(target=worker1) thread2 = threading.Thread(target=worker2) thread1.start() thread2.start() thread1.join() thread2.join() print("All threads have finished. Main thread exits.")
- 主线程等待多个子线程的完成: 当有多个子线程时,主线程可以使用
join
逐个等待它们的完成,以确保它们按照预期的顺序执行。
pythonCopy code import threading import time def worker(name, delay): print(f"{name} starts working.") time.sleep(delay) print(f"{name} finishes working.") threads = [] for i in range(5): thread = threading.Thread(target=worker, args=(f"Thread {i}", i)) threads.append(thread) thread.start() for thread in threads: thread.join() print("All threads have finished. Main thread exits.")
总之,join
方法用于线程之间的同步,确保主线程等待所需的子线程执行完成。