Added closing channels
This commit is contained in:
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")
|
||||
}
|
||||
Reference in New Issue
Block a user