Skip to content

Instantly share code, notes, and snippets.

@thanethomson
Created May 28, 2019 20:39
Show Gist options
  • Save thanethomson/d9f846b78af18d2d07dbd7e18cd8260a to your computer and use it in GitHub Desktop.
Save thanethomson/d9f846b78af18d2d07dbd7e18cd8260a to your computer and use it in GitHub Desktop.
Testing GetFreePort concurrent allocation with 1000 goroutines
package main
import (
"fmt"
"net"
"sync"
)
func GetFreePort() (int, error) {
addr, err := net.ResolveTCPAddr("tcp", "localhost:0")
if err != nil {
return 0, err
}
l, err := net.ListenTCP("tcp", addr)
if err != nil {
return 0, err
}
defer l.Close()
return l.Addr().(*net.TCPAddr).Port, nil
}
func allocatePorts(wg *sync.WaitGroup, maxAllocs int) {
wg.Add(1)
errors := 0
for i := 0; i < maxAllocs; i++ {
_, err := GetFreePort()
if err != nil {
fmt.Println("Got error", err)
errors++
}
}
if errors > 0 {
fmt.Printf("Got %d errors out of %d allocation attempts", errors, maxAllocs)
}
wg.Done()
}
func main() {
var wg sync.WaitGroup
maxAllocs := 1000
maxGoroutines := 1000
for i := 0; i < maxGoroutines; i++ {
go allocatePorts(&wg, maxAllocs)
}
wg.Wait()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment