Create a program that prints the numbers from 1 to 100 in order. Two concurrent goroutines should be used to print the numbers: one goroutine to print the odd numbers and another goroutine to print the even numbers. The challenge is to make sure the numbers are printed in ascending order while being generated by concurrent processes.
The given problem highlights a fundamental concept in concurrent programming: synchronization. When we have multiple goroutines running concurrently, we must ensure that they work together in a synchronized manner to achieve the correct output.
In our case, we have two goroutines: one for printing odd numbers and the other for printing even numbers. We need to ensure that they print the numbers in the correct order, even though they are running concurrently.
The code snippet provided leverages the Go programming language's concurrency primitives to solve the problem. Specifically, we use the sync.Mutex type to synchronize the two goroutines.
Here's a walkthrough of the code:
var evenMutex sync.Mutex
var oddMutex sync.Mutex
We define two mutexes: one for the even numbers (evenMutex)
and one for the odd numbers (oddMutex)
. These mutexes will be used to synchronize the goroutines.
evenMutex.Lock()
Initially, the evenMutex is locked to ensure that the odd-numbered goroutine starts first.
Two goroutines are defined and started. The odd-numbered goroutine locks the oddMutex and unlocks the evenMutex, while the even-numbered goroutine locks the evenMutex and unlocks the oddMutex.
go func() {
// Odd-numbered goroutine
...
}
go func() {
// Even-numbered goroutine
...
}
wg.Wait()
A sync.WaitGroup is used to wait for both goroutines to complete before the main function returns.
This example demonstrates how Go's concurrency primitives can be used to solve a classic synchronization problem. By carefully locking and unlocking mutexes in the correct order, the program ensures that the numbers from 1 to 100 are printed in ascending order by two concurrent goroutines.