03-携程同步

1. 代码结构

在这里插入图片描述

2 gorotine.go

package gorotine
import (
"fmt"
"sync"
"time"
)
//定义WG,用sync中的函数来同步数据
var WG sync.WaitGroup
func Read() {
for i :=0 ; i<=10 ; i++ {
WG.Add(1)
}
}
func Write() {
for i :=0 ; i <= 10 ; i++ {
time.Sleep(time.Second * 1)
fmt.Println("Done >",i)
WG.Done()
}
}

说明:
Add(n) 把计数器设置为n
Done() 每次把计数器-1
wait() 会阻塞代码的运行,直到计数器地值减为0
以上可知:
如果我把n 设置成2,那么我在下文main.go中可以打开两个协程执行WG.Write()
如果我把n仍设置成1,而在main.go中坚持打开两个协程执行WG.Write(),那写到5就报错了。除非我把Write()中的循环条件写成i=0;i<=21;i++

3 main.go

package main
import (
"814/gorotine"
"fmt"
"time"
)
func main () {
//主线程来读(上文可知,此时WG的计数器被设置为1)
gorotine.Read()
//开启一个协程来写(写完后计数器被-1,为0)
go gorotine.Write()
//主线程等待协程写完(阻塞代码,知道计数器为0)
gorotine.WG.Wait()
//协程写完后主线程打印一个标记
fmt.Println("All dome")
//主线程等两秒后退出
time.Sleep(time.Second * 2 )
}

4. 输出

Done > 0
Done > 1
Done > 2
Done > 3
Done > 4
Done > 5
Done > 6
Done > 7
Done > 8
Done > 9
Done > 10
All dome
Process finished with the exit code 0

posted on   运维开发玄德公  阅读(9)  评论(0编辑  收藏  举报  

相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示