我正在 8 个不同的 goroutine 上运行一个 cpu 密集型脚本。每个 goroutine 都至少需要几分钟才能完成,我想知道这样的事情是否可能:
for i := 0; i < len(input); i += 1 {
wait_for_number_of_processes_running_to_be_less_than_8
go calc_math_and_things(input[i])
}
Run Code Online (Sandbox Code Playgroud)
您可以使用缓冲通道返回 goroutine 的结果并指示终止,当您从此通道读取数据时,您将启动一个新的 go 例程。像这样的东西:
const maxNRoutine = 8
var routineCtr int
var resultCh = make(chan int, maxNRoutine)
for i := 0; i < len(input); i += 1 {
if routineCtr < maxNRoutines {
go calc_math_and_things(resultCh, input[i])
routineCtr++
continue
}
var result = <- resultCh // go routine is done, log result and start a new one
println(result)
go calc_math_and_things(resultCh, intput[i])
}
Run Code Online (Sandbox Code Playgroud)
在你的日常生活中:
func calc_math_and_things(resultCh chan<- int, input byte) {
// ... do some stuff
resultCh <- 1
}
Run Code Online (Sandbox Code Playgroud)