github.com/tcnksm/go@v0.0.0-20141208075154-439b32936367/src/runtime/race/testdata/rwmutex_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  	"sync"
     9  	"testing"
    10  	"time"
    11  )
    12  
    13  func TestRaceMutexRWMutex(t *testing.T) {
    14  	var mu1 sync.Mutex
    15  	var mu2 sync.RWMutex
    16  	var x int16 = 0
    17  	ch := make(chan bool, 2)
    18  	go func() {
    19  		mu1.Lock()
    20  		defer mu1.Unlock()
    21  		x = 1
    22  		ch <- true
    23  	}()
    24  	go func() {
    25  		mu2.Lock()
    26  		x = 2
    27  		mu2.Unlock()
    28  		ch <- true
    29  	}()
    30  	<-ch
    31  	<-ch
    32  }
    33  
    34  func TestNoRaceRWMutex(t *testing.T) {
    35  	var mu sync.RWMutex
    36  	var x, y int64 = 0, 1
    37  	ch := make(chan bool, 2)
    38  	go func() {
    39  		mu.Lock()
    40  		defer mu.Unlock()
    41  		x = 2
    42  		ch <- true
    43  	}()
    44  	go func() {
    45  		mu.RLock()
    46  		y = x
    47  		mu.RUnlock()
    48  		ch <- true
    49  	}()
    50  	<-ch
    51  	<-ch
    52  }
    53  
    54  func TestRaceRWMutexMultipleReaders(t *testing.T) {
    55  	var mu sync.RWMutex
    56  	var x, y int64 = 0, 1
    57  	ch := make(chan bool, 3)
    58  	go func() {
    59  		mu.Lock()
    60  		defer mu.Unlock()
    61  		x = 2
    62  		ch <- true
    63  	}()
    64  	go func() {
    65  		mu.RLock()
    66  		y = x + 1
    67  		mu.RUnlock()
    68  		ch <- true
    69  	}()
    70  	go func() {
    71  		mu.RLock()
    72  		y = x + 2
    73  		mu.RUnlock()
    74  		ch <- true
    75  	}()
    76  	<-ch
    77  	<-ch
    78  	<-ch
    79  	_ = y
    80  }
    81  
    82  func TestNoRaceRWMutexMultipleReaders(t *testing.T) {
    83  	var mu sync.RWMutex
    84  	x := int64(0)
    85  	ch := make(chan bool, 3)
    86  	go func() {
    87  		mu.Lock()
    88  		defer mu.Unlock()
    89  		x = 2
    90  		ch <- true
    91  	}()
    92  	go func() {
    93  		mu.RLock()
    94  		y := x + 1
    95  		_ = y
    96  		mu.RUnlock()
    97  		ch <- true
    98  	}()
    99  	go func() {
   100  		mu.RLock()
   101  		y := x + 2
   102  		_ = y
   103  		mu.RUnlock()
   104  		ch <- true
   105  	}()
   106  	<-ch
   107  	<-ch
   108  	<-ch
   109  }
   110  
   111  func TestNoRaceRWMutexTransitive(t *testing.T) {
   112  	var mu sync.RWMutex
   113  	x := int64(0)
   114  	ch := make(chan bool, 2)
   115  	go func() {
   116  		mu.RLock()
   117  		_ = x
   118  		mu.RUnlock()
   119  		ch <- true
   120  	}()
   121  	go func() {
   122  		time.Sleep(1e7)
   123  		mu.RLock()
   124  		_ = x
   125  		mu.RUnlock()
   126  		ch <- true
   127  	}()
   128  	time.Sleep(2e7)
   129  	mu.Lock()
   130  	x = 42
   131  	mu.Unlock()
   132  	<-ch
   133  	<-ch
   134  }