Skip to content

Instantly share code, notes, and snippets.

@deckarep
Last active December 22, 2016 20:59
Show Gist options
  • Save deckarep/0f851f24f341c3022a19271f1a8c31e8 to your computer and use it in GitHub Desktop.
Save deckarep/0f851f24f341c3022a19271f1a8c31e8 to your computer and use it in GitHub Desktop.
Unsafe without the use of locks
package main
import (
"fmt"
"math/rand"
"time"
)
const totalEnemies = 1
var gameStats *globalGameStats = &globalGameStats{}
type globalGameStats struct {
missed int
}
func (s *globalGameStats) incrementMissed() {
s.missed += 1
}
func (s *globalGameStats) dumpStats() {
fmt.Printf("Total missed: %d\n", s.missed)
}
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