SoFunction
Updated on 2025-03-04

Concurrency and parallelism in golang

Golang uses a CPU by default. At this time, the program cannot be concurrent, it can only be concurrent. Because there is always only one CPU running.

package main 
import (
        "fmt"
        "runtime"
)
 
//Concurrency and parallelismvar quit chan int = make(chan int) 
func loop() {
        for i := 0; i < 100; i++ { //To observe, run more                ("%d ", i)
        }
        quit <- 0
}
 
func main() {
        (2) // Use up to 2 cores 
        go loop()
        go loop()
 
        for i := 0; i < 2; i++ {
                <- quit
        }
}

(2) Setting to use 2 CPUs, which is truly parallel.

Supplement: Go multi-core parallelization

Create coroutines with the same logical number of CPU cores through goroutine, and the sum list is segmented, calculated and summarized.

The number of logical CPUs is obtained through (), and the subscript of the calculation list in each coroutine is calculated. After the calculation is completed, 1 is written into the channel.

By reading the number of ints into the channel, determine whether the coroutine operation is completed, and then sum it.

package main
import (
	"fmt"
	"runtime"
)
type Vector []float64
func (v Vector) DoSome(p, i, n int, u Vector, c chan int) {
	sum := 0.0
	for ; i < n; i++ {
		sum += u[i]
	}
	v[p] = sum
	c <- 1
}
const NCPU = 4
func (v Vector) DoAll(u Vector) {
	c := make(chan int, NCPU)
	for i := 0; i < NCPU; i++ {
		(i, i*len(u)/NCPU, (i+1)*len(u)/NCPU)
		go (i, i*len(u)/NCPU, (i+1)*len(u)/NCPU, u, c)
	}
	for i := 0; i < NCPU; i++ {
		<-c
	}
	sum := 0.0
	for _, value := range v {
		sum += value
	}
	(sum)
}
func main() {
	u := make([]float64, 64)
	for i := 0; i < 64; i++ {
		u[i] = float64(i)
	}
	var v Vector = make([]float64, NCPU)
	(u)
	ncpu := ()
	(ncpu)
}

The above is personal experience. I hope you can give you a reference and I hope you can support me more. If there are any mistakes or no complete considerations, I would like to give you advice.