diff --git a/closingchannels/closingchannels.go b/closingchannels/closingchannels.go new file mode 100644 index 0000000..3ff0e15 --- /dev/null +++ b/closingchannels/closingchannels.go @@ -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") +} diff --git a/main.go b/main.go index 40861eb..f4ebb0c 100644 --- a/main.go +++ b/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() }