gobyexample/closingchannels/closingchannels.go

47 lines
690 B
Go
Raw Normal View History

2024-04-28 11:15:17 +00:00
package closingchannels
import (
"fmt"
"math"
"math/rand"
"time"
)
func ClosingChannels() {
jobs := make(chan int, 5)
done := make(chan bool)
go func() {
for {
val, more := <-jobs
if more {
time.Sleep(time.Duration(rand.Intn(3)) * time.Second)
fmt.Printf("%d ^ %d is %f\n", val, 2, math.Pow(float64(val), 2))
} else {
fmt.Println("No more jobs, goroutine exiting")
done <- true
return
}
}
}()
for i := range 3 {
jobs <- i + 1
}
fmt.Println("Sent all jobs")
close(jobs)
<-done
_, more := <-jobs
if more {
fmt.Println("Uh-oh, jobs queue is not empty")
} else {
fmt.Println("Jobs queue is empty")
}
fmt.Println("Exiting")
}