Last active
December 22, 2016 21:23
-
-
Save deckarep/d545c2a126d63dd3b95490f5b65c2eb7 to your computer and use it in GitHub Desktop.
Demonstrates some safe code with the use of locks.
This file contains hidden or 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" | |
"math/rand" | |
"sync" | |
"time" | |
) | |
const totalEnemies = 2 | |
var gameStats *globalGameStats = &globalGameStats{} | |
type globalGameStats struct { | |
sync.RWMutex | |
missed int | |
} | |
func (s *globalGameStats) incrementMissed() { | |
s.Lock() | |
s.missed += 1 | |
s.Unlock() | |
} | |
func (s *globalGameStats) dumpStats() { | |
s.RLock() | |
fmt.Printf("Total missed: %d\n", s.missed) | |
s.RUnlock() | |
} | |
func main() { | |
for i := 0; i < totalEnemies; i++ { | |
go enemy() | |
} | |
time.Sleep(time.Second * 1) | |
gameStats.dumpStats() | |
} | |
func enemy() { | |
fmt.Println("Enemy created...") | |
for { | |
// Attempt attack. | |
if rand.Intn(100) >= 90 { | |
// Attack failed, record the miss. | |
gameStats.incrementMissed() | |
} else { | |
// Attack succeeded, do some logic to hurt the player. | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment