Created
July 18, 2019 02:10
-
-
Save jaysoncena/f2c98cba63f26a181c0ebb216b80d3de to your computer and use it in GitHub Desktop.
`[]byte` pool using sync.Pool
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"sync" | |
"net" | |
) | |
const MaxPacketSize = 4096 | |
var bufPool = sync.Pool { | |
New: func() interface{} { | |
return make([]byte, MaxPacketSize) | |
}, | |
} | |
func process(outChan chan []byte) { | |
for data := range outChan { | |
// process data | |
// Re-slice to maximum capacity and return it | |
// for re-use. This is important to guarantee that | |
// all calls to Get() will return a buffer of | |
// length MaxPacketSize. | |
bufPool.Put(data[:MaxPacketSize]) | |
} | |
} | |
func reader(conn net.PacketConn, outChan chan []byte) { | |
for { | |
data := bufPool.Get().([]byte) | |
n, _, err := conn.ReadFrom(data) | |
if err != nil { | |
break | |
} | |
outChan <- data[:n] | |
} | |
close(outChan) | |
} | |
func main() { | |
N := 3 | |
var wg sync.WaitGroup | |
outChan := make(chan []byte, N) | |
wg.Add(N) | |
for i := 0; i < N; i++ { | |
go func() { | |
process(outChan) | |
wg.Done() | |
}() | |
} | |
wg.Add(1) | |
conn, err := net.ListenPacket("udp", "localhost:10001") | |
if err != nil { | |
panic(err.Error()) | |
} | |
go func() { | |
reader(conn, outChan) | |
wg.Done() | |
}() | |
wg.Wait() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment