Concurrent Printing with Goroutines
This challenge introduces you to the fundamental concept of goroutines in Go – lightweight, concurrently executing functions. Understanding goroutines is crucial for writing efficient and responsive Go programs, especially when dealing with I/O-bound tasks or parallel computations. Your task is to create a program that prints numbers concurrently using goroutines.
Problem Description
You are required to write a Go program that prints numbers from 1 to n (inclusive) using goroutines. The program should launch a goroutine for each number. Each goroutine should print its assigned number to the console. The order of printing is not guaranteed and is part of the exercise – you should observe the concurrent nature of goroutines.
Key Requirements:
- The program should accept an integer
nas input, representing the upper limit of the numbers to be printed. - For each number from 1 to
n, a separate goroutine should be launched. - Each goroutine should print its assigned number to standard output (using
fmt.Println). - The main goroutine should wait for all launched goroutines to complete before exiting. This can be achieved using a
sync.WaitGroup.
Expected Behavior:
The program should print the numbers 1 to n to the console, but the order of printing may vary due to the concurrent execution of goroutines. The program should not terminate prematurely before all goroutines have finished printing their numbers.
Edge Cases to Consider:
nis 0: The program should not launch any goroutines and exit gracefully.nis 1: The program should launch one goroutine and print "1".- Large values of
n: The program should handle large values ofnwithout excessive resource consumption.
Examples
Example 1:
Input: 5
Output: (Order may vary)
1
2
3
4
5
Explanation: Five goroutines are launched, each printing a number from 1 to 5. The order of printing is not deterministic.
Example 2:
Input: 1
Output:
1
Explanation: One goroutine is launched, printing the number 1.
Example 3:
Input: 0
Output: (No output)
Explanation: No goroutines are launched, and the program exits.
Constraints
nwill be a non-negative integer.- The program should execute within a reasonable time frame (e.g., less than 1 second for
nup to 1000). - The program should not leak goroutines (i.e., all goroutines should eventually terminate).
Notes
- You will need to import the
fmtandsyncpackages. - Use
sync.WaitGroupto synchronize the main goroutine with the launched goroutines. Increment theWaitGroup.Add()before launching each goroutine, callwg.Done()inside each goroutine after printing, andwg.Wait()in the main goroutine before exiting. - Consider using a closure to capture the number to be printed within each goroutine.
- The primary goal is to demonstrate the creation and execution of goroutines, not to optimize for performance. Focus on correctness and clarity.