Skip to content

Instantly share code, notes, and snippets.

@duguying
Created November 16, 2016 07:40
Show Gist options
  • Save duguying/874c36be9cb980e3ed9607c5497c7d8e to your computer and use it in GitHub Desktop.
Save duguying/874c36be9cb980e3ed9607c5497c7d8e to your computer and use it in GitHub Desktop.
a demo for mutex lock
package main
import (
"fmt"
"sync"
"time"
)
type Nuclear struct {
l sync.Mutex
value string
}
func (nu *Nuclear) getValue() string {
// nu.l.Lock()
v := nu.value
// nu.l.Unlock()
return v
}
func (nu *Nuclear) setValue(v string) {
nu.l.Lock()
defer nu.l.Unlock()
nu.value = v
}
func main() {
var n Nuclear
go func() {
i := 0
for {
time.Sleep(time.Second)
n.setValue(fmt.Sprintf("hello world [%d]", i))
i = i + 1
}
}()
go func() {
for {
time.Sleep(time.Second)
val := n.getValue()
fmt.Println(val)
}
}()
for {
time.Sleep(time.Second)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment