10 Star 31 Fork 5

夏午茶 / sago

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
main.go 680 Bytes
一键复制 编辑 原始数据 按行查看 历史
gjy 提交于 2019-10-10 10:44 . del img
package main
import (
"context"
"fmt"
"time"
)
func main() {
x := foo()
fmt.Println(*x)
//ctx, cancel := context.WithTimeout(context.TODO(), time.Second*3)
//defer cancel() // 防止任务比超时时间短导致资源未释放
//// 启动协程
//go task(ctx)
//// 主协程需要等待,否则直pwd接退出
//time.Sleep(time.Second * 4)
}
func foo() *int {
t := 3
return &t
}
func task(ctx context.Context) {
ch := make(chan struct{}, 0)
// 真正的任务协程
go func() {
// 模拟两秒耗时任务
time.Sleep(time.Second * 5)
ch <- struct{}{}
}()
select {
case <-ch:
fmt.Println("done")
case <-ctx.Done():
fmt.Println("timeout")
}
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/xiawucha365/sago.git
git@gitee.com:xiawucha365/sago.git
xiawucha365
sago
sago
v1.1.0

搜索帮助

344bd9b3 5694891 D2dac590 5694891