github.com/EngineerKamesh/gofullstack@v0.0.0-20180609171605-d41341d7d4ee/volume1/section4/mutex/mutex.go (about)

     1  // An example of solving the data race condition using a mutex.
     2  package main
     3  
     4  import (
     5  	"fmt"
     6  	"sync"
     7  )
     8  
     9  var greetings string
    10  var howdyDone chan bool
    11  var mutex = &sync.Mutex{}
    12  
    13  func howdyGreetings() {
    14  
    15  	mutex.Lock()
    16  	greetings = "Howdy Gopher!"
    17  	mutex.Unlock()
    18  	howdyDone <- true
    19  }
    20  
    21  func main() {
    22  
    23  	howdyDone = make(chan bool, 1)
    24  	go howdyGreetings()
    25  	mutex.Lock()
    26  	greetings = "Hello Gopher!"
    27  	fmt.Println(greetings)
    28  	mutex.Unlock()
    29  	<-howdyDone
    30  }