乐闻世界logo
搜索文章和话题

How to make main thread wait for all child threads finish?

1个答案

1

In multithreaded programming, ensuring that the main thread waits for all child threads to complete is a common requirement. The methods to achieve this can vary across different programming languages. Here are some common approaches:

1. Using the Join Method

In many programming languages such as Java, C#, or Python, the Thread class typically has a join() method. This method causes the main thread to pause execution until the thread on which join() is called completes. Here is an example using Python:

python
import threading import time def worker(): # Simulate a time-consuming task time.sleep(2) print("Child thread completed") # Create threads threads = [] for i in range(5): thread = threading.Thread(target=worker) thread.start() threads.append(thread) # Wait for all child threads to complete for thread in threads: thread.join() print("All child threads have completed. Main thread continues execution.")

2. Using Countdown Latch or Semaphore

In some languages, you can use synchronization aids like CountDownLatch (Java) or Semaphore to manage thread execution. These tools allow one or more threads to wait for other threads to complete specific operations.

Java example using CountDownLatch:

java
import java.util.concurrent.CountDownLatch; public class Main { public static void main(String[] args) throws InterruptedException { int threadsCount = 5; CountDownLatch latch = new CountDownLatch(threadsCount); for (int i = 0; i < threadsCount; i++) { new Thread(() -> { try { // Simulate work Thread.sleep(2000); System.out.println("Child thread " + Thread.currentThread().getName() + " completed"); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } finally { latch.countDown(); } }).start(); } // Wait for all threads to complete latch.await(); System.out.println("All child threads have completed. Main thread continues execution."); } }

3. Using Future or Promise

In some modern programming languages, you can use Future, Promise, or related asynchronous programming patterns to manage asynchronous operations. The main thread can continue execution once all Future objects have completed.

Python example using concurrent.futures:

python
import concurrent.futures import time def worker(): time.sleep(2) return "Child thread completed" with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor: futures = [executor.submit(worker) for _ in range(5)] for future in concurrent.futures.as_completed(futures): print(future.result()) print("All child threads have completed. Main thread continues execution.")

Through the above examples, we can see that there are multiple ways to achieve the functionality of the main thread waiting for all child threads to complete. In practical applications, you can choose the most suitable method based on specific requirements and environment.

2024年6月29日 12:07 回复

你的答案