Source file test/atomicload.go

     1  // run
     2  
     3  // Copyright 2016 The Go Authors. All rights reserved.
     4  // Use of this source code is governed by a BSD-style
     5  // license that can be found in the LICENSE file.
     6  
     7  // Check that we do loads exactly once. The SSA backend
     8  // once tried to do the load in f twice, once sign extended
     9  // and once zero extended.  This can cause problems in
    10  // racy code, particularly sync/mutex.
    11  
    12  package main
    13  
    14  func f(p *byte) bool {
    15  	x := *p
    16  	a := int64(int8(x))
    17  	b := int64(uint8(x))
    18  	return a == b
    19  }
    20  
    21  func main() {
    22  	var x byte
    23  	const N = 1000000
    24  	c := make(chan struct{})
    25  	go func() {
    26  		for i := 0; i < N; i++ {
    27  			x = 1
    28  		}
    29  		c <- struct{}{}
    30  	}()
    31  	go func() {
    32  		for i := 0; i < N; i++ {
    33  			x = 2
    34  		}
    35  		c <- struct{}{}
    36  	}()
    37  
    38  	for i := 0; i < N; i++ {
    39  		if !f(&x) {
    40  			panic("non-atomic load!")
    41  		}
    42  	}
    43  	<-c
    44  	<-c
    45  }
    46  

View as plain text