panjf2000 / gnet

🚀 gnet is a high-performance, lightweight, non-blocking, event-driven networking framework written in pure Go.

Home Page:https://gnet.host

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

[Question]: Will the OnTraffic function be called concurrently?

Fish-watching-the-sea opened this issue · comments

Actions I've taken before I'm here

  • I've thoroughly read the documentations about this problem but still have no answer.
  • I've searched the Github Issues/Discussions but didn't find any similar problems that have been solved.
  • I've searched the internet for this problem but didn't find anything helpful.

Questions with details

有这样一段读取 UDP 数据的代码:

type PocNetManager struct {
	gnet.BuiltinEventEngine
	buffer         []byte
}

func (t *PocNetManager) OnTraffic(c gnet.Conn) (action gnet.Action) {
	n, err := c.Read(t.buffer)
	if err != nil {
		log.Error("read poc pkg error", t.myUID, zap.Error(err))
		return
	}
}

c 是一个 udpConn,我想知道 OnTraffic 函数会不会被并发调用。如果会并发调用,我可能需要把 OnTraffic 修改成下面这样:

func (t *PocNetManager) OnTraffic(c gnet.Conn) (action gnet.Action) {
        buffer := make([]byte, 10240)
	n, err := c.Read(buffer)
	if err != nil {
		log.Error("read poc pkg error", t.myUID, zap.Error(err))
		return
	}
}

感谢阅读,期望与你讨论,谢谢!

Code snippets (optional)

No response

OnTraffic will be invoked simultaneously on multi-cores machine with Multicore=true or NumEventLoop>0, so don't share the single buffer across all connections.