Created
November 16, 2016 07:40
-
-
Save duguying/874c36be9cb980e3ed9607c5497c7d8e to your computer and use it in GitHub Desktop.
a demo for mutex lock
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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