sách gpt4 ăn đã đi

for-loop - Vòng lặp song song

In lại 作者:IT王子 更新时间:2023-10-29 01:12:07 31 4
mua khóa gpt4 giày nike

我希望 for 循环使用 go 例程并行。我尝试使用 channel ,但没有用。我的主要问题是,我想在继续之前等待所有迭代完成。这就是为什么在它不起作用之前简单地编写 đi 的原因。我尝试使用 channel (我认为是错误的方式)但这让我的代码变得更慢

func createPopulation(populationSize int, individualSize int) []Individual {
population := make([]Individual, populationSize)

//i want this loop to be work parallel
for i := 0; i < len(population); i++ {
population[i] = createIndividual(individualSize)
}

return population
}

func createIndividual(size int) Individual {
var individual = Individual{make([]bool, size), 0}

for i := 0; i < len(individual.gene); i++ {
if rand.Intn(2)%2 == 1 {
individual.gene[i] = true
} khác {
individual.gene[i] = false
}
}

return individual
}

我的结构看起来像这样:

type Individual struct {
gene []bool
fitness int
}

câu trả lời hay nhất

所以基本上 goroutine 不应该返回一个值,而是将它插入一个 channel 。如果你想等待所有 goroutines 完成,你可以只计算 goroutines 的数量,或者使用 WaitGroup。在这个例子中,这是一个矫枉过正,因为大小是已知的,但无论如何这是一个很好的做法。这是一个修改后的例子:

gói chính

nhập khẩu (
"math/rand"
"đồng bộ"
)

type Individual struct {
gene []bool
fitness int
}


func createPopulation(populationSize int, individualSize int) []Individual {

// we create a slice with a capacity of populationSize but 0 size
// so we'll avoid extra unneeded allocations
population := make([]Individual, 0, populationSize)

// we create a buffered channel so writing to it won't block while we wait for the waitgroup to finish
ch := make(chan Individual, populationSize)

// we create a waitgroup - basically block until N tasks say they are done
wg := sync.WaitGroup{}

for i := 0; i < populationSize; i++ {

//we add 1 to the wait group - each worker will decrease it back
wg.Add(1)

//now we spawn a goroutine
go createIndividual(individualSize, ch, &wg)
}

// now we wait for everyone to finish - again, not a must.
// you can just receive from the channel N times, and use a timeout or something for safety
wg. Chờ()

// we need to close the channel or the following loop will get stuck
đóng(ch)

// we iterate over the closed channel and receive all data from it
for individual := range ch {

population = append(population, individual)
}
return population

}

func createIndividual(size int, ch chan Individual, wg *sync.WaitGroup) {

var individual = Individual{make([]bool, size), 0}

for i := 0; i < len(individual.gene); i++ {
if rand.Intn(2)%2 == 1 {
individual.gene[i] = true
} khác {
individual.gene[i] = false
}
}

// push the population object down the channel
ch <- individual
// let the wait group know we finished
wg.Xong()

}

关于for-loop - 并行 For 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24238820/

31 4 0
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress