2

I have a struct defined as follows:

type transactionList map[string]Transaction
type ActiveTransactions struct {
    mtx sync.Mutex
    trm transactionList
}

This struct has several methods defined:

func (act *ActiveTransactions) NewTransaction(id string, myPayload Payload) {
    act.mtx.Lock()
    act.trm[id] = Transaction{currentState: FirstState, Payload: myPayload}
    act.mtx.Unlock()
}

func (act *ActiveTransactions) GetState(id string) TState {
    act.mtx.Lock()
    state := act.trm[id].currentState
    act.mtx.Unlock()
    return state
}

func (act *ActiveTransactions) UpdateState(id string, newState TState) {
    act.mtx.Lock()
    tmp := act.trm[id]
    tmp.currentState = newState
    act.trm[id] = tmp
    act.mtx.Unlock()
}

This type is created once and is accessed by multiple goroutines. When I run the code it occasionally panics because of concurrent read/write map access (which is not entirely clear to me since access to the map is protected with sync.Mutex).

I have tried to run the code with -race option and it detects race condition as well (from the -race output I can see that race happens for GetState and NewTransaction methods)

What's happening here? Should trm be protected by mtx once Lock() is called? From the examples, I searched in the docs and tutorials the pattern looks ok. Obviously, something is wrong, but it eludes me.

Ivan Aracki
  • 4,861
  • 11
  • 59
  • 73
Vincent Chang
  • 65
  • 1
  • 4
  • 3
    The problem is likely outside of the code you've shown here. Try running vet on your program, which can catch accidental copying of mutexes. Though not the problem here, it's also easier to visually confirm locking if you defer the Unlock() immediately after Lock() – JimB Jan 14 '17 at 19:32
  • This code looks OK to me. Is this all the code that accesses `ActiveTransactions`? – Andy Schweig Jan 15 '17 at 03:01
  • 1
    @JimB running go vet helped, problem was located outside of this code indeed. Thanks – Vincent Chang Jan 15 '17 at 09:11
  • @VincentChang please check the answer data-race condition is actually there in the code ,mostly it is harmless – Sarath Sadasivan Pillai Jan 15 '17 at 09:18
  • If the question is unanswerable with the information given, and the original poster's problem is resolved, should this question be closed or deleted? – jochen Jun 27 '19 at 17:10

0 Answers0