Python 简明教程

Python - Joining the Threads

在 Python 中,加入线程意味着使用 join() 方法等待一个线程完成然后再继续执行其他线程。这在多线程编程中很有用,它确保在其他线程开始或继续执行之前完成某些线程。通过使用 join() 方法,你可以确保在一个线程或主程序继续执行之前另一个线程完成运行。在本教程中,你将获得关于 join() 方法的详细解释,并伴有合适的示例。

In Python, joining the threads means using the join() method to wait for one thread to finish before moving on to others. This is useful in multithreaded programming to make sure some threads are completed before starting or continuing with other threads. By using the join() method, you can make sure that one thread has finished running before another thread or the main program continues. In this tutorial you will get the detailed explain of the join() method with suitable examples.

Joining the Threads in Python

要加入 Python 中的线程,你可以使用 Thread.join() 模块中的 threading 方法。通常用于阻塞调用线程,直至调用 join() 的线程终止。终止可能是正常的(因为出现未处理的异常),或者直到可选的超时发生。你可以多次调用 join()。然而,如果你尝试加入当前线程或尝试在使用 start() 方法启动线程之前加入该线程,那么将会引发 RuntimeError 异常。

To join the threads in Python, you can use the Thread.join() method from the threading module. Which generally is used to block the calling thread until the thread on which join() was called terminates. The termination may be either normal, because of an unhandled exception − or until the optional timeout occurs. You can call join() multiple times. However, if you try to join the current thread or attempts to join a thread before starting it with the start() method, will raise the RuntimeError exception.

以下是 Thread.join() 方法的语法 -

Following is the syntax of the Thread.join() method −

thread.join(timeout)

其中, timeout 是一个可选参数,它采用一个浮点数字,以秒为单位(或其小数部分)指定最长等待时间。如果未提供此参数或提供 None,则该方法将阻塞,直至线程终止。

Where, the timeout is an optional parameter that takes a floating-point number specifying the maximum wait time in seconds (or fractions thereof). If it is not provided or None, the method will block until the thread terminates.

该方法总是返回 None。在调用 join() 之后,你可以使用 is_alive() 检查线程是否仍在运行。这有助于确定 join() 调用是否超时。

This method always returns None. After calling join(), you can use is_alive() to check if the thread is still running. This is useful to determine if the join() call timed out.

Example

以下示例演示了在多线程程序中使用 join() 。它启动两个线程(thread1 和 thread2)。最初,它阻塞主线程,直到 thread1 完成 my_function_1 的执行。thread1 完成后,调用 thread2.start(),然后调用 thread2.join() 来确保主线程等待直到 thread2 完成执行 my_function_2()。

The following example demonstrates the use of join() in a multithreaded program. It starts two threads (thread1 and thread2). Initially, it blocks the main thread until thread1 finishes executing the my_function_1. After thread1 completes, thread2.start() is called, followed by thread2.join() to ensure that the main thread waits until thread2 finishes executing my_function_2().

from threading import Thread
from time import sleep

def my_function_1(arg):
   for i in range(arg):
      print("Child Thread 1 running", i)
      sleep(0.5)

def my_function_2(arg):
   for i in range(arg):
      print("Child Thread 2 running", i)
      sleep(0.1)

# Create thread objects
thread1 = Thread(target=my_function_1, args=(5,))
thread2 = Thread(target=my_function_2, args=(3,))

# Start the first thread and wait for it to complete
thread1.start()
thread1.join()

# Start the second thread and wait for it to complete
thread2.start()
thread2.join()

print("Main thread finished...exiting")

执行上述代码后,将生成以下结果 −

When the above code is executed, it produces the following result −

Child Thread 1 running 0
Child Thread 1 running 1
Child Thread 1 running 2
Child Thread 1 running 3
Child Thread 1 running 4
Child Thread 2 running 0
Child Thread 2 running 1
Child Thread 2 running 2
Main thread finished...exiting

Example

这是另一个示例,演示带超时功能的 join() 方法如何允许等待线程完成一段指定时间,然后即使线程尚未完成也会继续执行。

Here is another example that demonstrates how the join() method with a timeout allows waiting for a thread to complete for a specified period, then proceeding even if the thread hasn’t finished.

from threading import Thread
from time import sleep

def my_function_1(arg):
   for i in range(arg):
      print("Child Thread 1 running", i)
      sleep(0.5)

def my_function_2(arg):
   for i in range(arg):
      print("Child Thread 2 running", i)
      sleep(0.1)

# Create thread objects
thread1 = Thread(target=my_function_1, args=(5,))
thread2 = Thread(target=my_function_2, args=(3,))

# Start the first thread and wait for 0.2 seconds
thread1.start()
thread1.join(timeout=0.2)

# Start the second thread and wait for it to complete
thread2.start()
thread2.join()

print("Main thread finished...exiting")

运行以上代码时,你可看到以下输出−

When you run the above code, you can see the following output −

Child Thread 1 running 0
Child Thread 2 running 0
Child Thread 2 running 1
Child Thread 2 running 2
Child Thread 1 running 1
Main thread finished...exiting
Child Thread 1 running 2
Child Thread 1 running 3
Child Thread 1 running 4