V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
ttxshang
V2EX  ›  Go 编程语言

请教一个 golang 问题

  •  
  •   ttxshang · 2023-03-05 23:20:32 +08:00 · 1541 次点击
    这是一个创建于 410 天前的主题,其中的信息可能已经有所发展或是发生改变。

    第一种写法

    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)
    	}
    }
    

    请问下上面两种写法,哪一种更好,为什么?除了以上方法还有其他更好的实现?感谢

    6 条回复    2023-03-06 17:08:26 +08:00
    Trim21
        1
    Trim21  
       2023-03-05 23:51:18 +08:00   ❤️ 1
    循环变量 topic 忘复制了吧?
    neoblackcap
        2
    neoblackcap  
       2023-03-06 01:05:37 +08:00
    你这样写,bus 变量在 goroutine 里面运用,需不需要加锁啊?
    qwerqqq
        3
    qwerqqq  
       2023-03-06 09:58:48 +08:00
    topic 的地址会变哦,你这么写有问题的,如果不考虑我觉得第二种效率可能要高一些
    yuancoder
        4
    yuancoder  
       2023-03-06 11:08:15 +08:00
    topic 变量只会在循环开始的时候声明一次,后面每次循环都只是修改这个变量的值。
    循环里面闭包引用的 topic 都是同一个,值会被修改。
    hzzhzzdogee
        5
    hzzhzzdogee  
       2023-03-06 16:25:21 +08:00
    赞同 3 楼
    concernedz
        6
    concernedz  
       2023-03-06 17:08:26 +08:00
    经典 for 循环 v 值变更,最后 topic 循环内需要重新声明下
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5677 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 35ms · UTC 02:05 · PVG 10:05 · LAX 19:05 · JFK 22:05
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.