package main
import (
"fmt"
"sync"
)
// wg is used to wait for the program to finish.
var wg sync.WaitGroup
func main() {
count := make(chan int)
// Add a count of two, one for each goroutine.
wg.Add(2)
fmt.Println("Start Goroutines")
// Launch a goroutine with label "Goroutine-1"
go printCounts("Goroutine-1", count)
// Launch a goroutine with label "Goroutine-2"
go printCounts("Goroutine-2", count)
fmt.Println("Communication of channel begins")
count <- 1
// Wait for the goroutines to finish.
fmt.Println("Waiting To Finish")
wg.Wait()
fmt.Println("\nTerminating the Program")
}
func printCounts(label string, count chan int) {
// Schedule the call to WaitGroup's Done to tell goroutine is completed.
defer wg.Done()
for val := range count {
fmt.Printf("Count: %d received from %s \n", val, label)
if val == 10 {
fmt.Printf("Channel Closed from %s \n", label)
// Close the channel
close(count)
return
}
val++
// Send count back to the other goroutine.
count <- val
}
}`
Please format the code in your question i a readable way. This can easily be done by selecting the code and hitting the </>
button at the top of the edut window.
1 Like
ok done! now can you explain the code to me?
printCounts
is not running ten times. There is a for val := range count
loop in printCounts
that keeps “ping-ponging” an incrementing count between Goroutine-1 and Goroutine-2 until that count gets to 10, at which point, the channel is closed so both Goroutines exit the loop and printCounts
.
2 Likes
thankyou Sean!
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.