大家在工作中使用go语言都是因为go语言中提供方便又简介的协成吧,只需一个go关键字就可以开启一个协成,今天为大家推荐一种go实现的多路复用代码,大家可以参考一下呀可以下方评论留言呦
go
package test_7
import (
"fmt"
"testing"
)
type binOp func(a, b int) int
func TestGoAll(t *testing.T) {
adder := startServer(func(a, b int) int { return a + b })
const N = 100
var reqs [N]Request
for i := 0; i < N; i++ {
req := &reqs[i]
req.a = i
req.b = i + N
req.replay = make(chan int)
adder <- req
}
for i := N - 1; i >= 0; i-- {
if <-reqs[i].replay != N+2*i {
fmt.Println("failed at", i)
} else {
fmt.Println("Request", i, "is ok!")
}
}
fmt.Println("done")
}
type Request struct {
a, b int
replay chan int
}
func run(op binOp, req *Request) {
req.replay <- op(req.a, req.b)
}
func server(op binOp, service chan *Request) {
for {
rep := <-service
go run(op, rep)
}
}
func startServer(op binOp) chan *Request {
reqChan := make(chan *Request)
go server(op, reqChan)
return reqChan
}