简体   繁体   English

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

[英]Data race with list.List concurrent access with mutexes

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. 使用-race命令运行测试时,我已将其范围缩小到尝试访问list.List在从list.List读取时,列表,但是我的互斥体似乎没有任何作用。

I have a number of *list.Lists inside of an array like so: 我在数组中有多个* list.Lists,如下所示:

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 在另一个goroutine中,还尝试读取并建立完整列表以返回

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()

The statement list := myListOfLists[someIndex] copies the array element to variable list . 语句list := myListOfLists[someIndex]将数组元素复制到变量list This copies the mutex, thus preventing the mutex from working. 这将复制互斥锁,从而阻止互斥锁工作。 The go vet command reports this problem. go vet命令报告此问题。

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 . 另一种方法是使用指向MyList的指针数组。 While you are at it, you might as well use a list value instead a list pointer in MyList : 在使用它时,最好在MyList使用列表值而不是列表指针:

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

var myListOfLists [10]*MyList
for i := range myListOfLists {
   myListOfLists[i] = &MyList{}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM