gpt4 book ai didi

concurrency - Golang 并发数组访问

转载 作者:IT老高 更新时间:2023-10-28 13:10:51 25 4
gpt4 key购买 nike

当每个 goroutine 在一个 slice 上工作时,从多个 goroutine 访问同一个数组是否安全,指向同一个底层数组但不重叠?

喜欢:

var arr [100]int
sliceA := arr[:50]
sliceB := arr[50:]

go WorkOn(sliceA)
go WorkOn(sliceB)

想象一下“WorkOn”会做一些花哨的事情。

最佳答案

只要保证区域不重叠就可以了。

保证我的意思是:谁在sliceA上工作,应该被允许做sliceA = append(sliceA, a, b, c)。因为那样它就会开始进入 sliceB 的领域。

此处相关的是 Go 1.2 的一些文档:这涉及一个新的语言元素:3-index slices:

Go 1.2 adds the ability to specify the capacity as well as the length when using a slicing operation on an existing array or slice. A slicing operation creates a new slice by describing a contiguous section of an already-created array or slice:

var array [10]int
slice := array[2:4]

The capacity of the slice is the maximum number of elements that the slice may hold, even after reslicing; it reflects the size of the underlying array. In this example, the capacity of the slice variable is 8.

Go 1.2 adds new syntax to allow a slicing operation to specify the capacity as well as the length. A second colon introduces the capacity value, which must be less than or equal to the capacity of the source slice or array, adjusted for the origin. For instance,

slice = array[2:4:7]

sets the slice to have the same length as in the earlier example but its capacity is now only 5 elements (7-2). It is impossible to use this new slice value to access the last three elements of the original array.

In this three-index notation, a missing first index ([:i:j]) defaults to zero but the other two indices must always be specified explicitly. It is possible that future releases of Go may introduce default values for these indices.

Further details are in the design document.

关于concurrency - Golang 并发数组访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22517614/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com