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 { select {
case <-g.kill: case <-g.kill:
log.Printf("game %s: received kill signal, dying gracefully", g.id) log.Printf("game %s: received kill signal, dying gracefully", g.id)
gameLock.Lock() games.Lock()
delete(games, g.id) delete(games.m, g.id)
gameLock.Unlock() games.Unlock()
return return
case p := <-g.register: case p := <-g.register:
g.players[p] = true 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) _g := NewGame(new_game_name, *width, *height)
go _g.run() go _g.run()
gameLock.Lock() games.Lock()
games[new_game_name] = _g games.m[new_game_name] = _g
log.Printf("%+v", games) log.Printf("%+v", games)
gameLock.Unlock() games.Unlock()
w.Write([]byte(fmt.Sprintf(`{"id": "%s"}`, new_game_name))) w.Write([]byte(fmt.Sprintf(`{"id": "%s"}`, new_game_name)))
} }
func listGames(w http.ResponseWriter, req *http.Request) { func listGames(w http.ResponseWriter, req *http.Request) {
gameLock.RLock() games.RLock()
defer gameLock.RUnlock() defer games.RUnlock()
ids := make([]string, 0) ids := make([]string, 0)
for id, _ := range games { for id, _ := range games.m {
ids = append(ids, id) ids = append(ids, id)
} }
if err := json.NewEncoder(w).Encode(ids); err != nil { if err := json.NewEncoder(w).Encode(ids); err != nil {
@ -51,9 +51,9 @@ func addPlayer(ws *websocket.Conn) {
return return
} }
gameLock.Lock() games.Lock()
game, ok := games[gid.Id] game, ok := games.m[gid.Id]
gameLock.Unlock() games.Unlock()
if !ok { if !ok {
log.Println("ERROR: game not found") 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 delta float64
var games map[string]*game
var idg *IdGenerator var idg *IdGenerator
var gameLock sync.RWMutex
type MapLock struct {
m map[string]*game
sync.RWMutex
}
var games MapLock
func main() { func main() {
rand.Seed(time.Now().UnixNano()) rand.Seed(time.Now().UnixNano())
flag.Parse() flag.Parse()
games = make(map[string]*game) games = MapLock{m: make(map[string]*game)}
idg = NewIdGenerator() idg = NewIdGenerator()
delta = float64(*tick) / 1000 delta = float64(*tick) / 1000