Source file src/internal/runtime/atomic/xchg8_test.go

     1  // Copyright 2024 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  //go:build 386 || amd64 || arm || arm64 || ppc64 || ppc64le
     6  
     7  package atomic_test
     8  
     9  import (
    10  	"internal/runtime/atomic"
    11  	"testing"
    12  )
    13  
    14  func TestXchg8(t *testing.T) {
    15  	var a [16]uint8
    16  	for i := range a {
    17  		next := uint8(i + 50)
    18  		a[i] = next
    19  	}
    20  	b := a
    21  
    22  	// Compare behavior against non-atomic implementation. Expect the operation
    23  	// to work at any byte offset and to not clobber neighboring values.
    24  	for i := range a {
    25  		next := uint8(i + 100)
    26  		pa := atomic.Xchg8(&a[i], next)
    27  		pb := b[i]
    28  		b[i] = next
    29  		if pa != pb {
    30  			t.Errorf("atomic.Xchg8(a[%d]); %d != %d", i, pa, pb)
    31  		}
    32  		if a != b {
    33  			t.Errorf("after atomic.Xchg8(a[%d]); %d != %d", i, a, b)
    34  		}
    35  		if t.Failed() {
    36  			break
    37  		}
    38  	}
    39  }
    40  
    41  func BenchmarkXchg8(b *testing.B) {
    42  	var x [512]uint8 // give byte its own cache line
    43  	sink = &x
    44  	for i := 0; i < b.N; i++ {
    45  		atomic.Xchg8(&x[255], uint8(i))
    46  	}
    47  }
    48  
    49  func BenchmarkXchg8Parallel(b *testing.B) {
    50  	var x [512]uint8 // give byte its own cache line
    51  	sink = &x
    52  	b.RunParallel(func(pb *testing.PB) {
    53  		i := uint8(0)
    54  		for pb.Next() {
    55  			atomic.Xchg8(&x[255], i)
    56  			i++
    57  		}
    58  	})
    59  }
    60  

View as plain text