embedded the mutex into the games global (one fewer global)
This commit is contained in:
parent
c6b480fa1e
commit
1ca4679b04
6
game.go
6
game.go
@ -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
18
http.go
@ -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
11
main.go
@ -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
|
||||
|
Loading…
Reference in New Issue
Block a user