drci47425 2017-01-14 16:56 采纳率: 100%
浏览 33

使用互斥锁保护Golang结构,仍然可以通过锁定检测到种族

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.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
    • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
    • ¥15 CSAPPattacklab
    • ¥15 一直显示正在等待HID—ISP
    • ¥15 Python turtle 画图
    • ¥15 关于大棚监测的pcb板设计
    • ¥15 stm32开发clion时遇到的编译问题
    • ¥15 lna设计 源简并电感型共源放大器
    • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
    • ¥15 Vue3地图和异步函数使用