douzhang8033 2018-12-07 17:32
浏览 49
已采纳

与列表进行数据竞争。使用互斥体列出并发访问

I'm getting a data race and I can't quite figure out why. Running my tests with the -race command I've narrowed it down to trying to access a list.List while reading from it, but my Mutexes don't seem to do anything.

I have a number of *list.Lists inside of an array like so:

type MyList struct {
    mutex sync.Mutex
    *list.List
}

type SomeObj struct {
    data string
}

var myListOfLists [10]MyList

I'm reading and writing from the list like so:

list := myListOfLists[someIndex]
list.mutex.Lock()
for e := list.Front(); e != nil; e = e.Next() {
        if (...) {
            list.MoveToFront(e)
        }
}
list.mutex.Unlock()

and in another goroutine also trying to read and build a full list to return

var fullCopy []*SomeObj
list := myListOfLists[someIndex]

list.mutex.Lock()
for e := list.Front(); e != nil; e = e.Next() {
        fullCopy = append(fullCopy, e.Value.(SomeObj))
}
list.mutex.Unlock()
  • 写回答

1条回答 默认 最新

  • duanpenpan5796 2018-12-07 17:57
    关注

    The statement list := myListOfLists[someIndex] copies the array element to variable list. This copies the mutex, thus preventing the mutex from working. The go vet command reports this problem.

    You can avoid the copy by using a pointer to the array element:

    list := &myListOfLists[someIndex]
    

    Another approach is to use an array of pointers to MyList. While you are at it, you might as well use a list value instead a list pointer in MyList:

    type MyList struct {
        mutex sync.Mutex
        list.List
    }
    
    var myListOfLists [10]*MyList
    for i := range myListOfLists {
       myListOfLists[i] = &MyList{}
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题