Created
April 1, 2020 03:15
-
-
Save JesseYan/79d38772a499fd6d746683c2c59e93b7 to your computer and use it in GitHub Desktop.
create pool using gorutines,and consumes in async
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
create a pool using gorutines, and run in async
this run in sync, and keep the pool is always 4 in capacity util the end.
print