Skip to content

Instantly share code, notes, and snippets.

@JesseYan
Created April 1, 2020 03:15
Show Gist options
  • Save JesseYan/79d38772a499fd6d746683c2c59e93b7 to your computer and use it in GitHub Desktop.
Save JesseYan/79d38772a499fd6d746683c2c59e93b7 to your computer and use it in GitHub Desktop.
create pool using gorutines,and consumes in async
package main
import (
"fmt"
"sync"
"time"
)
var wg sync.WaitGroup
func main() {
ch := make(chan int, 4)
go produce(ch)
time.Sleep(2 * time.Second)
consume(ch)
}
func produce(ch chan int) {
for i := 0; i < 16; i++ {
ch <- i
fmt.Println("successfully wrote", i, "to ch")
}
close(ch)
}
func consume(ch chan int) {
for c := range ch {
wg.Add(1)
go doSomething(c)
}
wg.Wait()
}
func doSomething(c int) {
fmt.Println("consume:", c)
time.Sleep(10 * time.Second)
wg.Done()
}
@JesseYan
Copy link
Author

JesseYan commented Apr 1, 2020

create a pool using gorutines, and run in async

compare with the pool gist doc

this run in sync, and keep the pool is always 4 in capacity util the end.

print

successfully wrote 0 to ch
successfully wrote 1 to ch
successfully wrote 2 to ch
successfully wrote 3 to ch
consume: 0
successfully wrote 4 to ch
successfully wrote 5 to ch
consume: 2
consume: 6
consume: 1
consume: 4
consume: 3
successfully wrote 6 to ch
successfully wrote 7 to ch
successfully wrote 8 to ch
successfully wrote 9 to ch
successfully wrote 10 to ch
successfully wrote 11 to ch
consume: 5
consume: 12
consume: 7
consume: 10
consume: 11
successfully wrote 12 to ch
successfully wrote 13 to ch
successfully wrote 14 to ch
successfully wrote 15 to ch
consume: 15
consume: 13
consume: 14
consume: 8
consume: 9

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