Get help on this challenge

Debugging20


Please read this explanation before attempting debugging challenges.


My Go code for a simple multithreaded counter seems to have a race condition somewhere even though I'm locking with a mutex. What am I doing wrong?

package main

import (
    "fmt"
    "sync"
)

type Counter struct {
    n int
    sync.Mutex
}

func (c *Counter) Inc() {
    c.Lock()
    defer c.Unlock()
    c.n++
}

func (c Counter) Show() {
    c.Lock()
    defer c.Unlock()
    fmt.Printf("Count: %d\n", c.n)
}

func main() {
    c := &Counter{0, sync.Mutex{}}
    wg := sync.WaitGroup{}
    for i := 0; i < 50; i++ {
        wg.Add(1)
        go func() {
            defer wg.Done()
            c.Inc()
            c.Show()
        }()
    }
    wg.Wait()
}

/*
When I run the this program with the -race flag I get this output:
> go run -race debugging20.go
==================
WARNING: DATA RACE
Write at 0x00c420078198 by goroutine 7:
  sync/atomic.CompareAndSwapInt32()
      /usr/local/go/src/runtime/race_amd64.s:293 +0xb 
  sync.(*Mutex).Lock()
      /usr/local/go/src/sync/mutex.go:48 +0x4d
  main.(*Counter).Inc()
      /home/ynori7/debugging20.go:14 +0x47
  main.main.func1()
      /home/ynori7/debugging20.go:32 +0x62

Previous read at 0x00c420078198 by goroutine 6:
  main.main.func1()
      /home/ynori7/debugging20.go:33 +0x7c

Goroutine 7 (running) created at:
  main.main()
      /home/ynori7/debugging20.go:34 +0xe9

Goroutine 6 (finished) created at:
  main.main()
      /home/ynori7/debugging20.go:34 +0xe9
==================
*/

Downloadable source code can be found here.


You must be logged in to play. Login or register here



Challenge by ynori7.