Added closing channels
This commit is contained in:
parent
c41662bff8
commit
e55d715892
46
closingchannels/closingchannels.go
Normal file
46
closingchannels/closingchannels.go
Normal 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")
|
||||
}
|
6
main.go
6
main.go
@ -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()
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user