embedded the mutex into the games global (one fewer global)

This commit is contained in:
Stephen McQuay 2013-09-05 18:14:41 -07:00
parent c6b480fa1e
commit 1ca4679b04
3 changed files with 20 additions and 15 deletions

View File

@ -47,9 +47,9 @@ func (g *game) run() {
select {
case <-g.kill:
log.Printf("game %s: received kill signal, dying gracefully", g.id)
gameLock.Lock()
delete(games, g.id)
gameLock.Unlock()
games.Lock()
delete(games.m, g.id)
games.Unlock()
return
case p := <-g.register:
g.players[p] = true

18
http.go
View File

@ -22,19 +22,19 @@ func startGame(w http.ResponseWriter, req *http.Request) {
_g := NewGame(new_game_name, *width, *height)
go _g.run()
gameLock.Lock()
games[new_game_name] = _g
games.Lock()
games.m[new_game_name] = _g
log.Printf("%+v", games)
gameLock.Unlock()
games.Unlock()
w.Write([]byte(fmt.Sprintf(`{"id": "%s"}`, new_game_name)))
}
func listGames(w http.ResponseWriter, req *http.Request) {
gameLock.RLock()
defer gameLock.RUnlock()
games.RLock()
defer games.RUnlock()
ids := make([]string, 0)
for id, _ := range games {
for id, _ := range games.m {
ids = append(ids, id)
}
if err := json.NewEncoder(w).Encode(ids); err != nil {
@ -51,9 +51,9 @@ func addPlayer(ws *websocket.Conn) {
return
}
gameLock.Lock()
game, ok := games[gid.Id]
gameLock.Unlock()
games.Lock()
game, ok := games.m[gid.Id]
games.Unlock()
if !ok {
log.Println("ERROR: game not found")

11
main.go
View File

@ -18,15 +18,20 @@ var height = flag.Float64("height", 550, "height of field")
var delta float64
var games map[string]*game
var idg *IdGenerator
var gameLock sync.RWMutex
type MapLock struct {
m map[string]*game
sync.RWMutex
}
var games MapLock
func main() {
rand.Seed(time.Now().UnixNano())
flag.Parse()
games = make(map[string]*game)
games = MapLock{m: make(map[string]*game)}
idg = NewIdGenerator()
delta = float64(*tick) / 1000