
第一种写法
func (bus *es) PublicAll(topics []*EventTopic) { for _, topic := range topics { bus.mutex.Lock() h, ok := bus.handlers[topic.Topic] bus.mutex.Unlock() if !ok { continue } bus.client.Subscribe(topic.Topic, byte(topic.QoSValue), func(c mqtt.Client, m mqtt.Message) { go func(h EventHandler) { defer func() { if err := recover(); err != nil { fmt.Printf("goroutine panic: %+v \r\n", err) } }() h(topic.Topic, m) }(h) }) } } 第二种写法
func (bus *es) PublicAll(topics []*EventTopic) { for _, topic := range topics { bus.mutex.Lock() h, ok := bus.handlers[topic.Topic] bus.mutex.Unlock() if !ok { continue } go func(h EventHandler) { defer func() { if err := recover(); err != nil { fmt.Printf("goroutine panic: %+v \r\n", err) } }() bus.client.Subscribe(topic.Topic, byte(topic.QoSValue), func(c mqtt.Client, m mqtt.Message) { h(topic.Topic, m) }) }(h) } } 请问下上面两种写法,哪一种更好,为什么?除了以上方法还有其他更好的实现?感谢
1 Trim21 2023 年 3 月 5 日 循环变量 topic 忘复制了吧? |
2 neoblackcap 2023 年 3 月 6 日 你这样写,bus 变量在 goroutine 里面运用,需不需要加锁啊? |
3 qwerqqq 2023 年 3 月 6 日 topic 的地址会变哦,你这么写有问题的,如果不考虑我觉得第二种效率可能要高一些 |
4 yuancoder 2023 年 3 月 6 日 topic 变量只会在循环开始的时候声明一次,后面每次循环都只是修改这个变量的值。 循环里面闭包引用的 topic 都是同一个,值会被修改。 |
5 hzzhzzdogee 2023 年 3 月 6 日 赞同 3 楼 |
6 concernedz 2023 年 3 月 6 日 经典 for 循环 v 值变更,最后 topic 循环内需要重新声明下 |