Terry-Mao / goim

goim
https://goim.io/
MIT License
7.2k stars 1.78k forks source link

多个线程处理同一个连接的目的 #374

Closed banzhihang closed 3 years ago

banzhihang commented 3 years ago
// InitTCP listen all tcp.bind and start accept connections.
func InitTCP(server *Server, addrs []string, accept int) (err error) {
    var (
        bind     string
        listener *net.TCPListener
        addr     *net.TCPAddr
    )
    for _, bind = range addrs {
        if addr, err = net.ResolveTCPAddr("tcp", bind); err != nil {
            log.Errorf("net.ResolveTCPAddr(tcp, %s) error(%v)", bind, err)
            return
        }
        if listener, err = net.ListenTCP("tcp", addr); err != nil {
            log.Errorf("net.ListenTCP(tcp, %s) error(%v)", bind, err)
            return
        }
        log.Infof("start tcp listen: %s", bind)
        // split N core accept
        for i := 0; i < accept; i++ {
            go acceptTCP(server, listener)
        }
    }
    return
}

comet server_tcp.go中,开cpu核心数量的线程来处理同一个端口的目的是什么,有大佬能解答一下吗

wuyuancai commented 3 years ago

因为accept 是阻塞的,多个协程去处理,以CPU核数来作为线程(协程)数,充分压榨CPU性能