Skip to content

Instantly share code, notes, and snippets.

@drush
Last active January 22, 2018 19:51
Show Gist options
  • Save drush/2e6de34a0a3822a7617865d06bbdec75 to your computer and use it in GitHub Desktop.
Save drush/2e6de34a0a3822a7617865d06bbdec75 to your computer and use it in GitHub Desktop.
Buffered vs Unbuffered channel behavior in golang
package main
import (
"fmt"
"sync"
"time"
)
func main() {
// Bufferered channel. Remove the 50 to see how an unbuffered channel behaves differently
jobs := make(chan int, 5)
jobsToo := make(chan int, 5)
var wg sync.WaitGroup
go func() {
defer wg.Done()
for event := range jobs {
fmt.Println("\treceived:", event)
time.Sleep(200 * time.Millisecond)
fmt.Printf("\tprocessed: %d\tqueue: %d\n", event, len(jobs))
}
fmt.Println("No more jobs in the queue, queue has been closed.")
}()
go func() {
defer wg.Done()
for event := range jobsToo {
// fmt.Println("\treceived:", event)
time.Sleep(20 * time.Millisecond)
fmt.Printf("\tJOBS2 processed: %d\tqueue: %d\n", event, len(jobs))
}
fmt.Println("No more jobs in the JOBS2 queue, queue has been closed.")
}()
wg.Add(2)
for i := 1; i < 10; i++ {
jobs <- i
jobsToo <- i
fmt.Printf("val: %d\tq: %d\n", i, len(jobs))
time.Sleep(10 * time.Millisecond)
}
close(jobs)
close(jobsToo)
wg.Wait()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment