1
0
mirror of https://github.com/taigrr/go-fastping synced 2025-01-18 05:03:15 -08:00

Use sync.WaitGroup for waiting to finish sendICMP4

This commit is contained in:
Tatsushi Demachi 2014-08-03 07:36:16 +09:00
parent 88c0127fe9
commit 69db984e45

View File

@ -40,6 +40,7 @@ import (
"log" "log"
"math/rand" "math/rand"
"net" "net"
"sync"
"syscall" "syscall"
"time" "time"
) )
@ -262,8 +263,7 @@ func (p *Pinger) sendICMP4(conn *net.IPConn) (map[string]*net.IPAddr, error) {
p.id = rand.Intn(0xffff) p.id = rand.Intn(0xffff)
p.seq = rand.Intn(0xffff) p.seq = rand.Intn(0xffff)
queue := make(map[string]*net.IPAddr) queue := make(map[string]*net.IPAddr)
qlen := 0 var wg sync.WaitGroup
sent := make(chan bool)
for k, v := range p.addrs { for k, v := range p.addrs {
bytes, err := (&icmpMessage{ bytes, err := (&icmpMessage{
Type: icmpv4EchoRequest, Code: 0, Type: icmpv4EchoRequest, Code: 0,
@ -273,18 +273,14 @@ func (p *Pinger) sendICMP4(conn *net.IPConn) (map[string]*net.IPAddr, error) {
}, },
}).Marshal() }).Marshal()
if err != nil { if err != nil {
for i := 0; i < qlen; i++ { wg.Wait()
p.debugln("sendICMP4(): wait goroutine")
<-sent
p.debugln("sendICMP4(): join goroutine")
}
return queue, err return queue, err
} }
queue[k] = v queue[k] = v
qlen++
p.debugln("sendICMP4(): Invoke goroutine") p.debugln("sendICMP4(): Invoke goroutine")
wg.Add(1)
go func(ra *net.IPAddr, b []byte) { go func(ra *net.IPAddr, b []byte) {
for { for {
if _, _, err := conn.WriteMsgIP(bytes, nil, ra); err != nil { if _, _, err := conn.WriteMsgIP(bytes, nil, ra); err != nil {
@ -297,14 +293,10 @@ func (p *Pinger) sendICMP4(conn *net.IPConn) (map[string]*net.IPAddr, error) {
break break
} }
p.debugln("sendICMP4(): WriteMsgIP End") p.debugln("sendICMP4(): WriteMsgIP End")
sent <- true wg.Done()
}(v, bytes) }(v, bytes)
} }
for i := 0; i < qlen; i++ { wg.Wait()
p.debugln("sendICMP4(): wait goroutine")
<-sent
p.debugln("sendICMP4(): join goroutine")
}
p.debugln("sendICMP4(): End") p.debugln("sendICMP4(): End")
return queue, nil return queue, nil
} }