main.go

package main

import (
"fmt"
"jiechen"
)

var (
intChan chan int
resMap map[int]float64 = make(map[int]float64)
)

func main() {
for i := 1; i <= 10; i++ {
jiechen.WG.Add(1)
go jiechen.Calc2(i)
}
jiechen.WG.Wait()
}

func test2() {
for i := 1; i <= 100; i++ {
res := jiechen.Calc(i)
fmt.Println(res)
resMap[i] = res
}
fmt.Println("====================")
fmt.Println(resMap)
}

func test1() {
intChan = make(chan int, 3)
intChan <- 11
intChan <- 22
intChan <- 33
fmt.Println(<-intChan)
}

jiechen.go

package jiechen

import (
"fmt"
"sync"
)

var (
WG sync.WaitGroup
Lock sync.Mutex
)

func Calc2(i int) {
defer WG.Done()
Lock.Lock()
var res float64 = 1
resmap := make(map[int]float64)
for j := 1; j <= i; j++ {
res *= float64(j)
}
resmap[i] = res
fmt.Println(resmap)
Lock.Unlock()
}

func Calc(i int) float64 {
var res float64 = 1
for idx := 1; idx <= i; idx++ {
res *= float64(idx)
}
return res
}

go.mod

module channel

go 1.16

require jiechen v1.1.1

replace jiechen => ./jiechen

日志输出

go代码sync.Mutex同步加锁示例:并行求阶乘_i++