github.com/cockroachdb/tools@v0.0.0-20230222021103-a6d27438930d/go/ssa/interp/testdata/src/sync/sync.go (about)

     1  package sync
     2  
     3  // Rudimentary implementation of a mutex for interp tests.
     4  type Mutex struct {
     5  	c chan int // Mutex is held when held c!=nil and is empty. Access is guarded by g.
     6  }
     7  
     8  func (m *Mutex) Lock() {
     9  	c := ch(m)
    10  	<-c
    11  }
    12  
    13  func (m *Mutex) Unlock() {
    14  	c := ch(m)
    15  	c <- 1
    16  }
    17  
    18  // sequentializes Mutex.c access.
    19  var g = make(chan int, 1)
    20  
    21  func init() {
    22  	g <- 1
    23  }
    24  
    25  // ch initializes the m.c field if needed and returns it.
    26  func ch(m *Mutex) chan int {
    27  	<-g
    28  	defer func() {
    29  		g <- 1
    30  	}()
    31  	if m.c == nil {
    32  		m.c = make(chan int, 1)
    33  		m.c <- 1
    34  	}
    35  	return m.c
    36  }