#Map len() issues, concurrency and pointers

3 messages · Page 1 of 1 (latest)

safe ruin
#

code:

timersToWaitFor := map[int]*chan int{
    0: &ws.EnemyMoveEndChan,
    1: &ws.TimeNWeatherEndChan,
    2: &ws.MonitorEndChan,
    3: &ws.LogCleanerEndChan,
    4: &ws.LeaveManager.Cancel,
}
timersCompleted := make(map[int]bool, 0)
for index, timer := range timersToWaitFor {
    go func(t *chan int, i int, completedMap *map[int]bool) {
        *t <- 1
        m := *completedMap
        m[i] = true
        log.Printf("WorldSession::CloseSession - Timer %d Completed %d of %d", i, len(timersCompleted), len(timersToWaitFor))
    }(timer, index, &timersCompleted)
}

timeElapsed := 0
for len(timersCompleted) < len(timersToWaitFor) {
    log.Printf("WorldSession::CloseSession - Waiting for timers to end.  %d of %d completed.", len(timersCompleted), len(timersToWaitFor))
    time.Sleep(100 * time.Millisecond)
    timeElapsed = timeElapsed + 100
    if timeElapsed > 10000 {
        log.Printf("WorldSession::CloseSession - Timers took too long to end.  This shouldnt happen.")
        break
    }
}

The goal is to close down a bunch of goroutines concurrently as they run on differently timed intervals.
This code is producing some odd output and I'm not entirely sure why, it appears the len of the map changes, the code was originally a bit simpler but in effort to solve the issue its 'changed' into this.

Here is the output: https://hastebin.com/share/apakojerix.go

brittle kelp
#

~

  1. you donn't need pointer for map and channel.
  2. there is a data race in your code, run it with -race flag/
safe ruin