马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
×
概述
看了几篇同步,异步,壅闭和非壅闭的文章,感觉照旧云里雾里的。本文联合本身的明白写几个例子加深印象,大概明白有误。大佬们可以帮助品评指正。
个人明白同步/异步,壅闭/非壅闭是站在差异角度看的概念。
同步/异步:站在被调用方视角看,同步会实验调用方的哀求,哀求竣事后返回实验结果给调用方。异步会先相应调用方哀求,在实验调用方哀求,末了给结果。
壅闭/非壅闭:站在调用方视角看,壅闭会等候被调用方相应,在等候期间啥事也不干。非壅闭在等候被调用方相应期间可以干别的事。
示例
本文以买咖啡为例先容同步,异步,壅闭和非壅闭的几种情况。
同步壅闭
- type Customer struct{}
-
- func (c *Customer) BuyCoffee() {
- coffee, ok := worker.MakeCoffee()
- if !ok {
- fmt.Println("make coffee failed")
- }
- fmt.Println("get my coffee", coffee.Name)
- }
-
- type Coffee struct {
- Name string
- }
-
- type Worker struct{}
-
- var worker Worker
-
- func (w *Worker) MakeCoffee() (coffee *Coffee, ok bool) {
- fmt.Println("start make coffee")
- time.Sleep(1 * time.Second)
- fmt.Println("make coffee finish")
-
- return &Coffee{Name: "latte"}, true
- }
-
- func main() {
- hxia := &Customer{}
- hxia.BuyCoffee()
- }
复制代码 同步壅闭,当用户买咖啡时,咖啡师开始做用户的这一杯咖啡,用户等咖啡做好。咖啡师做好后把咖啡给用户,用户拿到咖啡。这是同步逻辑,可以看到同步壅闭,当咖啡师做咖啡时,用户啥也不干,服从较低。
异步壅闭
[code]type Customer struct{} func (c *Customer) BuyCoffee() { go worker.MakeCoffee() for coffeeWithResult := range coffeec { if !coffeeWithResult.Result { fmt.Println("make coffee failed") } if coffeeWithResult.Coffee != nil { fmt.Println("get my coffee", coffeeWithResult.Coffee.Name) } } } type Coffee struct { Name string } type Worker struct{} var worker Worker func (w *Worker) Do() { fmt.Println("start make coffee") time.Sleep(1 * time.Second) fmt.Println("make coffee finish") } type CoffeeWithResult struct { Coffee *Coffee Result bool } var coffeec = make(chan CoffeeWithResult) func (w *Worker) MakeCoffee() { fmt.Println("response to customer that I'm start to make your coffee") coffeec |