Skip to content

Commit

Permalink
change the way of use waitgroup
Browse files Browse the repository at this point in the history
  • Loading branch information
gansidui committed Nov 1, 2015
1 parent bc20b14 commit 5e2c02c
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 9 deletions.
19 changes: 11 additions & 8 deletions conn.go
Expand Up @@ -121,22 +121,19 @@ func (c *Conn) AsyncWritePacket(p Packet, timeout time.Duration) (err error) {

// Do it
func (c *Conn) Do() {
defer c.srv.waitGroup.Done()
if !c.srv.callback.OnConnect(c) {
return
}

c.srv.waitGroup.Add(3)
go c.handleLoop()
go c.readLoop()
go c.writeLoop()
asyncDo(c.handleLoop, c.srv.waitGroup)
asyncDo(c.readLoop, c.srv.waitGroup)
asyncDo(c.writeLoop, c.srv.waitGroup)
}

func (c *Conn) readLoop() {
defer func() {
recover()
c.Close()
c.srv.waitGroup.Done()
}()

for {
Expand All @@ -163,7 +160,6 @@ func (c *Conn) writeLoop() {
defer func() {
recover()
c.Close()
c.srv.waitGroup.Done()
}()

for {
Expand All @@ -189,7 +185,6 @@ func (c *Conn) handleLoop() {
defer func() {
recover()
c.Close()
c.srv.waitGroup.Done()
}()

for {
Expand All @@ -210,3 +205,11 @@ func (c *Conn) handleLoop() {
}
}
}

func asyncDo(fn func(), wg *sync.WaitGroup) {
wg.Add(1)
go func() {
fn()
wg.Done()
}()
}
5 changes: 4 additions & 1 deletion server.go
Expand Up @@ -54,7 +54,10 @@ func (s *Server) Start(listener *net.TCPListener, acceptTimeout time.Duration) {
}

s.waitGroup.Add(1)
go newConn(conn, s).Do()
go func() {
newConn(conn, s).Do()
s.waitGroup.Done()
}()
}
}

Expand Down

0 comments on commit 5e2c02c

Please sign in to comment.