goroutine编程
1. goroutine池
- 本质上是生产者消费者模型
- 在工作中我们通常会使用可以指定启动的goroutine数量–
worker pool
模式,控制goroutine
的数量,防止goroutine
泄漏和暴涨。
- 一个简易的
work pool
示例代码如下:
package main
import (
"fmt"
"time"
)
func worker(id int, jobs <-chan int, results chan<- int) {
for j := range jobs {
fmt.Printf("worker:%d start job:%d\n", id, j)
time.Sleep(time.Second)
fmt.Printf("worker:%d end job:%d\n", id, j)
results <- j * 2
}
}
func main() {
jobs := make(chan int, 100)
results := make(chan int, 100)
for w := 1; w <= 3; w++ {
go worker(w, jobs, results)
}
for j := 1; j <= 5; j++ {
jobs <- j
}
close(jobs)
for a := 1; a <= 5; a++ {
v := <-results
fmt.Println(v)
}
}
2. 打印奇数偶数
2.1. 一个无缓冲管道实现
- 首先我们这里通过make(chan int),开辟的通道是一种无缓冲通道
- 所以当对这个缓冲通道写的时候,
会一直阻塞等到某个协程对这个缓冲通道读
- 而这里我讲
ch <- true 理解为生产
,他却是需要等到某个协程读了再能继续运行
package main
import (
"fmt"
"sync"
)
var wg sync.WaitGroup
func printJS(ch chan bool) {
defer wg.Done()
for i := 1; i <= 9; i += 2 {
fmt.Println("js", i)
ch <- true
<-ch
}
}
func printOS(ch chan bool) {
defer wg.Done()
for i := 2; i <= 10; i += 2 {
<-ch
fmt.Println("os", i)
ch <- false
}
}
func main() {
ch := make(chan bool)
wg.Add(2)
go printJS(ch)
go printOS(ch)
wg.Wait()
}
2.2. 两个无缓冲管道实现
package main
import (
"fmt"
"sync"
)
var ch1 = make(chan bool)
var ch2 = make(chan bool)
var wg sync.WaitGroup
func go1JS() {
defer wg.Done()
for i := 1; i <= 10; i += 2 {
<-ch1
fmt.Println(i)
ch2 <- true
}
<-ch1
}
func go2OS() {
defer wg.Done()
for i := 2; i <= 10; i += 2 {
<-ch2
fmt.Println(i)
ch1 <- true
}
}
func main() {
wg.Add(2)
go go1JS()
go go2OS()
ch1 <- true
wg.Wait()
}
3. 超时控制
3.1. 基础版
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
ch := make(chan bool)
var ret int
go func() {
ret = rpc()
<-ch
}()
count := 0
for count < 10 {
if ret != 0 {
fmt.Println(ret)
break
}
time.Sleep(time.Second)
count += 1
}
if count >= 10 {
ch <- false
fmt.Println("timeout")
}
}
func rpc() int {
cost := rand.Intn(15) + 1
fmt.Printf("rpc will cost %d seconds\n", cost)
time.Sleep(time.Duration(cost) * time.Second)
return cost
}
func init() {
rand.Seed(time.Now().UnixNano())
}
3.2. time.After控制超时
package main
import (
"fmt"
"time"
)
func main() {
workDoneCh := make(chan bool, 1)
go func() {
LongTimeWork()
workDoneCh <- true
}()
select {
case <-workDoneCh:
fmt.Println("Success!")
case <-time.After(3 * time.Second):
fmt.Println("timeout")
}
}
func LongTimeWork() {
time.Sleep(time.Second * 2)
}