github.com/aloncn/graphics-go@v0.0.1/src/runtime/race/testdata/io_test.go (about)

     1  // Copyright 2012 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package race_test
     6  
     7  import (
     8  	"fmt"
     9  	"io/ioutil"
    10  	"net/http"
    11  	"os"
    12  	"path/filepath"
    13  	"testing"
    14  	"time"
    15  )
    16  
    17  func TestNoRaceIOFile(t *testing.T) {
    18  	x := 0
    19  	path, _ := ioutil.TempDir("", "race_test")
    20  	fname := filepath.Join(path, "data")
    21  	go func() {
    22  		x = 42
    23  		f, _ := os.Create(fname)
    24  		f.Write([]byte("done"))
    25  		f.Close()
    26  	}()
    27  	for {
    28  		f, err := os.Open(fname)
    29  		if err != nil {
    30  			time.Sleep(1e6)
    31  			continue
    32  		}
    33  		buf := make([]byte, 100)
    34  		count, err := f.Read(buf)
    35  		if count == 0 {
    36  			time.Sleep(1e6)
    37  			continue
    38  		}
    39  		break
    40  	}
    41  	_ = x
    42  }
    43  
    44  func TestNoRaceIOHttp(t *testing.T) {
    45  	x := 0
    46  	go func() {
    47  		http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    48  			x = 41
    49  			fmt.Fprintf(w, "test")
    50  			x = 42
    51  		})
    52  		err := http.ListenAndServe("127.0.0.1:23651", nil)
    53  		if err != nil {
    54  			t.Fatalf("http.ListenAndServe: %v", err)
    55  		}
    56  	}()
    57  	time.Sleep(1e7)
    58  	x = 1
    59  	_, err := http.Get("http://127.0.0.1:23651")
    60  	if err != nil {
    61  		t.Fatalf("http.Get: %v", err)
    62  	}
    63  	x = 2
    64  	_, err = http.Get("http://127.0.0.1:23651")
    65  	if err != nil {
    66  		t.Fatalf("http.Get: %v", err)
    67  	}
    68  	x = 3
    69  }