Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Modifying dynamically MaxIdleConnsPerHost on http.Transport creates a data race
package main
import (
"fmt"
"io/ioutil"
"math/rand"
"net/http"
"net/http/httptest"
"sync"
"testing"
"time"
)
var server = httptest.NewServer(mux)
var mux = http.NewServeMux()
var wg sync.WaitGroup
var t *http.Transport
var c *http.Client
func init() {
mux.HandleFunc("/", HelloServer)
t = &http.Transport{}
c = &http.Client{Transport: t}
}
func HelloServer(w http.ResponseWriter, req *http.Request) {
time.Sleep(1 * time.Second)
fmt.Fprintf(w, ".")
}
func TestMain(t *testing.T) {
for i := 0; i < 100; i++ {
wg.Add(1)
go client()
}
wg.Wait()
}
func client() {
defer wg.Done()
//t.MaxIdleConnsMutex.Lock()
t.MaxIdleConnsPerHost = rand.Intn(10) + 1
//t.MaxIdleConnsMutex.Unlock()
r, err := c.Get(server.URL)
if err != nil {
fmt.Println(err.Error())
}
defer r.Body.Close()
body, _ := ioutil.ReadAll(r.Body)
fmt.Print(string(body))
}
@go-loco

This comment has been minimized.

Copy link
Owner Author

go-loco commented Mar 27, 2016

Running this gist with go test -race creates a data race.

$ go test -race

==================
WARNING: DATA RACE
Write by goroutine 9:
  github.com/go-loco.client()
      /Users/hernan/apps/go/src/github.com/go-loco/s_test.go:49 +0xa6

Previous write by goroutine 8:
  github.com/go-loco.client()
      /Users/hernan/apps/go/src/github.com/go-loco/s_test.go:49 +0xa6

Goroutine 9 (running) created at:
  github.com/go-loco.TestMain()
      /Users/hernan/apps/go/src/github.com/go-loco/s_test.go:37 +0x62
  testing.tRunner()
      /Users/hernan/apps/go/go-src/go/src/testing/testing.go:547 +0xbf

Goroutine 8 (running) created at:
  github.com/go-loco.TestMain()
      /Users/hernan/apps/go/src/github.com/go-loco/s_test.go:37 +0x62
  testing.tRunner()
      /Users/hernan/apps/go/go-src/go/src/testing/testing.go:547 +0xbf
==================
....................................................................................................PASS
Found 1 data race(s)
exit status 66
FAIL    github.com/go-loco  2.157s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.