Source file src/runtime/race/testdata/pool_test.go

     1  // Copyright 2016 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 TestRacePool(t *testing.T) {
    14  	// Pool randomly drops the argument on the floor during Put.
    15  	// Repeat so that at least one iteration gets reuse.
    16  	for i := 0; i < 10; i++ {
    17  		c := make(chan int)
    18  		p := &sync.Pool{New: func() any { return make([]byte, 10) }}
    19  		x := p.Get().([]byte)
    20  		x[0] = 1
    21  		p.Put(x)
    22  		go func() {
    23  			y := p.Get().([]byte)
    24  			y[0] = 2
    25  			c <- 1
    26  		}()
    27  		x[0] = 3
    28  		<-c
    29  	}
    30  }
    31  
    32  func TestNoRacePool(t *testing.T) {
    33  	for i := 0; i < 10; i++ {
    34  		p := &sync.Pool{New: func() any { return make([]byte, 10) }}
    35  		x := p.Get().([]byte)
    36  		x[0] = 1
    37  		p.Put(x)
    38  		go func() {
    39  			y := p.Get().([]byte)
    40  			y[0] = 2
    41  			p.Put(y)
    42  		}()
    43  		time.Sleep(100 * time.Millisecond)
    44  		x = p.Get().([]byte)
    45  		x[0] = 3
    46  	}
    47  }
    48  

View as plain text