Created
March 27, 2016 13:05
-
-
Save go-loco/810fe53d8aee8879b8d1 to your computer and use it in GitHub Desktop.
Modifying dynamically MaxIdleConnsPerHost on http.Transport creates a data race
This file contains 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 ( | |
"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)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Running this gist with go test -race creates a data race.
$ go test -race