同步/异步和壅闭/非壅闭学习条记 [复制链接]
发表于 2025-11-13 10:27:19 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
概述

看了几篇同步,异步,壅闭和非壅闭的文章,感觉照旧云里雾里的。本文联合本身的明白写几个例子加深印象,大概明白有误。大佬们可以帮助品评指正。
个人明白同步/异步,壅闭/非壅闭是站在差异角度看的概念。
同步/异步:站在被调用方视角看,同步会实验调用方的哀求,哀求竣事后返回实验结果给调用方。异步会先相应调用方哀求,在实验调用方哀求,末了给结果。
壅闭/非壅闭:站在调用方视角看,壅闭会等候被调用方相应,在等候期间啥事也不干。非壅闭在等候被调用方相应期间可以干别的事。
示例

本文以买咖啡为例先容同步,异步,壅闭和非壅闭的几种情况。
同步壅闭
  1. type Customer struct{}  
  2.   
  3. func (c *Customer) BuyCoffee() {  
  4.     coffee, ok := worker.MakeCoffee()  
  5.     if !ok {  
  6.        fmt.Println("make coffee failed")  
  7.     }  
  8.     fmt.Println("get my coffee", coffee.Name)  
  9. }  
  10.   
  11. type Coffee struct {  
  12.     Name string  
  13. }  
  14.   
  15. type Worker struct{}  
  16.   
  17. var worker Worker  
  18.   
  19. func (w *Worker) MakeCoffee() (coffee *Coffee, ok bool) {  
  20.     fmt.Println("start make coffee")  
  21.     time.Sleep(1 * time.Second)  
  22.     fmt.Println("make coffee finish")  
  23.   
  24.     return &Coffee{Name: "latte"}, true  
  25. }  
  26.   
  27. func main() {   
  28.     hxia := &Customer{}  
  29.     hxia.BuyCoffee()  
  30. }
复制代码
同步壅闭,当用户买咖啡时,咖啡师开始做用户的这一杯咖啡,用户等咖啡做好。咖啡师做好后把咖啡给用户,用户拿到咖啡。这是同步逻辑,可以看到同步壅闭,当咖啡师做咖啡时,用户啥也不干,服从较低。
异步壅闭

[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
回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表