标签:you src lazy span cond https func var sleep
package main import ( "fmt" "time" ) var jobs chan int var results chan int func work(id int, jobs <-chan int, results chan<- int) { for i := range jobs { fmt.Printf("gorutine:%d;开始任务:%d;\n", id, i) time.Sleep(time.Second) fmt.Printf("gorutine:%d;结束任务:%d;\n", id, i) results <- i * 2 } } //5个任务给3个gorutine工作 func main() { jobs := make(chan int, 100) results := make(chan int, 100) //开启3个Goroutine for w := 1; w <= 3; w++ { go work(w, jobs, results) } //5个任务 for i := 1; i <= 5; i++ { jobs <- i } close(jobs) //输出结果 for j := 1; j <= 5; j++ { <-results } }
结果:
参考:https://www.youtube.com/watch?v=HmHgAGvV_yc&list=PLLPsLcbaFY20fG25TVsrCeAgXrBSrZDYU&index=87
标签:you src lazy span cond https func var sleep
原文地址:https://www.cnblogs.com/dzw159/p/14930933.html