Skip to content

Instantly share code, notes, and snippets.

@rohanthewiz
Created December 10, 2015 07:14
Show Gist options
  • Save rohanthewiz/cf9d09c0c148edc02f8b to your computer and use it in GitHub Desktop.
Save rohanthewiz/cf9d09c0c148edc02f8b to your computer and use it in GitHub Desktop.
Using channels and waitgroups for effective communication with goroutines
package main
import (
"fmt"
"sync"
)
// Send words onto a channel until we receive on the done channel
func emit(wch chan string, dch chan struct{}, wg *sync.WaitGroup) {
words := []string{"The", "quick", "brown", "fox"}
i := 0
for {
select { // Perform an operation on a channel that is not blocked
case wch <- words[i]: // queue up a word if channel can receive
i += 1
if i == len(words) { wch <- "\n"; i = 0 } // there is no limit
case <- dch: // Is there anything on the done channel or is it closed?
fmt.Println("\nDone message rcx'd")
wg.Done()
return
}
}
}
func main() {
word_ch := make(chan string)
done_ch := make(chan struct{})
var wg sync.WaitGroup
wg.Add(1)
go emit(word_ch, done_ch, &wg) // start the word pump // Waitgroup must be passed by reference
for i := 0; i < 15; i++ {
fmt.Printf("%s ", <- word_ch) // pull a word off the channel
}
close(done_ch) // Once we close this channel, it can be received from so it signals any listening goroutines.
wg.Wait()
}
@rohanthewiz
Copy link
Author

Thanks to John Graham and Dave Cheney for the tutorials.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment