Added closing channels

This commit is contained in:
Sangeeth Sudheer 2024-04-28 16:45:17 +05:30
parent c41662bff8
commit e55d715892
Signed by: x
GPG Key ID: F6D06ECE734C57D1
2 changed files with 50 additions and 2 deletions

View File

@ -0,0 +1,46 @@
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")
}

View File

@ -8,7 +8,8 @@ package main
// import "git.sangeeth.dev/gobyexample/channels"
// import "git.sangeeth.dev/gobyexample/cselect"
// import "git.sangeeth.dev/gobyexample/timeouts"
import "git.sangeeth.dev/gobyexample/selectdefault"
// import "git.sangeeth.dev/gobyexample/selectdefault"
import "git.sangeeth.dev/gobyexample/closingchannels"
func main() {
// runes.Runes()
@ -19,5 +20,6 @@ func main() {
// channels.Channels()
// cselect.Select()
// timeouts.Timeouts()
selectdefault.SelectDefault()
// selectdefault.SelectDefault()
closingchannels.ClosingChannels()
}