Skip to content

Commit

Permalink
Use mutext for player model
Browse files Browse the repository at this point in the history
  • Loading branch information
AmirRezaM75 committed Feb 24, 2024
1 parent a0b6c80 commit 7334896
Showing 1 changed file with 12 additions and 0 deletions.
12 changes: 12 additions & 0 deletions server/models/player.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"log"
"skullking/constants"
"strconv"
"sync"
)

type Player struct {
Expand All @@ -22,17 +23,28 @@ type Player struct {
IsConnected bool
// To keep track of closed channel
IsClosed bool
mutex sync.Mutex
}

// Different scenarios for 'close of closed channel'
// 1) If user opens duplicate tab and close the first one

func (player *Player) Kick() {

// We are using mutex to make sure IsClosed value is evaluated correctly
// when reading its value at the same time.
// https://go101.org/article/channel-closing.html
player.mutex.Lock()

defer player.mutex.Unlock()

if !player.IsClosed {
close(player.Message)
player.IsClosed = true
}

// First we need to check if it's nil or not
// we call kick method in game_handler, and player may has no connection
if player.Connection != nil {
_ = player.Connection.Close()
}
Expand Down

0 comments on commit 7334896

Please sign in to comment.