From aa5118b1298a11655ea5acf583d858b1017c8af7 Mon Sep 17 00:00:00 2001
From: Brad Fitzpatrick
-const NCPU = 4 // number of CPU cores +const numCPU = 4 // number of CPU cores func (v Vector) DoAll(u Vector) { - c := make(chan int, NCPU) // Buffering optional but sensible. - for i := 0; i < NCPU; i++ { - go v.DoSome(i*len(v)/NCPU, (i+1)*len(v)/NCPU, u, c) + 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 < NCPU; i++ { + for i := 0; i < numCPU; i++ { <-c // wait for one task to complete } // All done. } --
-The current implementation of the Go runtime
-will not parallelize this code by default.
-It dedicates only a single core to user-level processing. An
-arbitrary number of goroutines can be blocked in system calls, but
-by default only one can be executing user-level code at any time.
-It should be smarter and one day it will be smarter, but until it
-is if you want CPU parallelism you must tell the run-time
-how many goroutines you want executing code simultaneously. There
-are two related ways to do this. Either run your job with environment
-variable GOMAXPROCS
set to the number of cores to use
-or import the runtime
package and call
-runtime.GOMAXPROCS(NCPU)
.
-A helpful value might be runtime.NumCPU()
, which reports the number
-of logical CPUs on the local machine.
-Again, this requirement is expected to be retired as the scheduling and run-time improve.
+Rather than create a constant value for numCPU, we can ask the runtime what
+value is appropriate.
+The function runtime.NumCPU
+returns the number of hardware CPU cores in the machine, so we could write
+var numCPU = runtime.NumCPU() ++
+There is also a function
+runtime.GOMAXPROCS
,
+which reports (or sets)
+the user-specified number of cores that a Go program can have running
+simultaneously.
+It defaults to the value of runtime.NumCPU
but can be
+overridden by setting the similarly named shell environment variable
+or by calling the function with a positive number. Calling it with
+zero just queries the value.
+Therefore if we want to honor the user's resource request, we should write
+
+var numCPU = runtime.GOMAXPROCS(0) +
Be sure not to confuse the ideas of concurrencyâstructuring a program as independently executing componentsâand parallelismâexecuting -- 2.50.0