The following excerpt is from https://go.dev/doc/effective_go#parallel.
We launch the pieces independently in a loop, one per CPU. They can complete in any order but it doesn't matter; we just count the completion signals by draining the channel after launching all the goroutines.
const numCPU = 4 // number of CPU cores
func (v Vector) DoAll(u Vector) {
c := make(chan int, numCPU) // Buffering optional but sensible.
for i := 0; i < numCPU; i {
go v.DoSome(i*len(v)/numCPU, (i 1)*len(v)/numCPU, u, c)
}
// Drain the channel.
for i := 0; i < numCPU; i {
<-c // wait for one task to complete
}
// All done.
}
Why does the article specify "one per CPU"? Multiple goroutines need not be executed on different CPUs. In fact, the last paragraph in the sub-section reminds the reader that concurrency is not parallelism:
Be sure not to confuse the ideas of concurrency—structuring a program as independently executing components—and parallelism—executing calculations in parallel for efficiency on multiple CPUs.
CodePudding user response:
Does a goroutine necessarily run on a different CPU?
No, but it might.
Nothing to see here.
why the article specifies "one per CPU"
It could have said 5 or 2. Really there is nothing of importance hidden here. This is just an example, not the specification of goroutine scheduling.
CodePudding user response:
Why does the article specify "one per CPU"? Multiple goroutines need not be executed on different CPUs. In fact, the last paragraph in the sub-section reminds the reader that concurrency is not parallelism:
goroutines are mapped with OS threads (M:N) and each goroutine can use a maximum of one thread at a time but you can not predict whether it is using the 1 CPU to execute all the 4 (GOMAXPROCS) goutines or it is use 2 cpu or 3 cpu or all 4 cpu.It is depending upon many factor's and all these complexity is hidden by go runtime