package main

import (
"fmt"
"sync"
)

var (
sum int
wg sync.WaitGroup
lock sync.Mutex
)

func main() {
wg.Add(2)
go func() {
defer wg.Done()
lock.Lock()
for i := 1; i <= 100000; i++ {
sum += i
}
lock.Unlock()
}()
go func() {
defer wg.Done()
lock.Lock()
for i := 1; i <= 100000; i++ {
sum -= i
}
lock.Unlock()
}()
wg.Wait()
fmt.Println(sum)
}

go锁实现代码同步执行:sync.WaitGroup和sync.Mutex_后端