Skip to content

Instantly share code, notes, and snippets.

@JesseYan
Created April 1, 2020 02:48
Show Gist options
  • Save JesseYan/c137f8d572f8038b97e06a94c335bdb7 to your computer and use it in GitHub Desktop.
Save JesseYan/c137f8d572f8038b97e06a94c335bdb7 to your computer and use it in GitHub Desktop.
create pool using gorutines
package main
import (
"fmt"
"time"
)
func main() {
ch := make(chan int, 4)
go write(ch)
time.Sleep(2 * time.Second)
consume(ch)
}
func write(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 {
fmt.Println("consume:", c)
time.Sleep(1 * time.Second)
}
}
@JesseYan
Copy link
Author

JesseYan commented Apr 1, 2020

create a pool for capacity 4

and produce 1 job and then consume 1, and so...

1.produce is not the same goroutine as consume

line 9 to 12

2. Must close channel after produce; otherwise, consume will show error:

all goroutines are asleep - deadlock

line 20 in func write

print

create a pool for capacity 4
first, fill full of capacity;
and then, produce 1 job and then consume 1, and so.
last, consume last 4 jobs.

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
consume: 1
successfully wrote 5 to ch
consume: 2
successfully wrote 6 to ch
consume: 3
successfully wrote 7 to ch
successfully wrote 8 to ch
consume: 4
consume: 5
successfully wrote 9 to ch
consume: 6
successfully wrote 10 to ch
consume: 7
successfully wrote 11 to ch
consume: 8
successfully wrote 12 to ch
successfully wrote 13 to ch
consume: 9
successfully wrote 14 to ch
consume: 10
consume: 11
successfully wrote 15 to ch
consume: 12
consume: 13
consume: 14
consume: 15

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