gorountine demo
package controllers
import (
"fmt"
"github.com/astaxie/beego"
"time"
)
type GoDemoController struct {
beego.Controller
}
// go协程打印顺序不一致(并行)
// @router /go/demo [*]
func (this *GoDemoController) Demo() {
for i := 0; i < 10; i++ { // 启动10个任务
go cal(i)
}
time.Sleep(2 * time.Second)
this.Ctx.WriteString("demos")
}
func cal(i int) {
fmt.Printf("i= %d\n", i)
}
/**
channel demo
*/
// 打印顺序不一致(并行)
// @router /go/channel/demo [*]
func (this *GoDemoController) ChannelDemo() {
Channel := make(chan bool, 10) // 带缓冲
for i := 0; i < 10; i++ {
// 为什么go访问? 如果是无缓冲的channel,在一个goroutine中实现发送和接收会发生死锁
go cal1(i, Channel)
}
for j := 0; j < 10; j++ {
关注
打赏