diff --git a/device.go b/device.go index abb409f..f9f6707 100644 --- a/device.go +++ b/device.go @@ -11,6 +11,7 @@ import ( "os/exec" gen "slimming/proto/gen" "strings" + "sync" "sync/atomic" "time" @@ -31,6 +32,14 @@ type NetCard struct { server *RPCServer clientMap map[string]*RPCClient + + lock sync.Mutex +} + +func (nc *NetCard) Lock(do func()) { + nc.lock.Lock() + defer nc.lock.Unlock() + do() } type RPCClient struct { @@ -176,11 +185,14 @@ func (nc *NetCard) runRead() { var rframe ethernet.Frame rframe.Resize(1500) - n, err := ifce.Read([]byte(rframe)) - if err != nil { - log.Fatal(err) - } - rframe = rframe[:n] + nc.Lock(func() { + n, err := ifce.Read([]byte(rframe)) + if err != nil { + log.Fatal(err) + } + rframe = rframe[:n] + }) + if !waterutil.IsIPv4(rframe) || waterutil.IPv4Source(rframe).Equal(net.IPv4(0, 0, 0, 0)) { continue } @@ -260,12 +272,15 @@ func (nc *NetCard) runWrite() { log.Printf("get wframes decode len: %d", len(bufs[0])) - for _, buf := range bufs { - _, err := ifce.Write(buf) - if err != nil { - log.Panic(err) + nc.Lock(func() { + for _, buf := range bufs { + _, err := ifce.Write(buf) + if err != nil { + log.Panic(err) + } } - } + }) + } }