Go-waitGroup的那些事
程序员文章站
2022-05-05 12:30:38
...
- Add() 和 Wait() 最好不要放在不同的 goroutine, 避免并发执行.
- 同一个 Once 实例调用多次 Do 方法, 只有一个函数会被调用, 但是其他的函数会阻塞, 等待 Unlock.
上代码, 自己品:
package main
import (
"fmt"
"sync"
)
func main() {
var wg sync.WaitGroup
wg.Add(2)
go func() {
defer wg.Done()
fmt.Println(1)
}()
go func() {
defer wg.Done()
fmt.Println(2)
}()
wg.Wait()
fmt.Println("Done")
}
package main
import (
"fmt"
"sync"
"time"
)
func main() {
var wg sync.WaitGroup
wg.Add(1)
go func() {
//defer wg.Done()
fmt.Println(1)
wg.Done()
wg.Add(1)
time.Sleep(time.Second * 1)
wg.Done()
}()
wg.Wait() // panic: sync: WaitGroup is reused before previous Wait has returned
fmt.Println("Done")
}
package main
import (
"fmt"
"sync"
"time"
)
func main() {
var wg sync.WaitGroup
times := 10
batch := 3
for i := 0; i < times; i++ {
wg.Add(batch)
for j := 0; j < batch; j++ {
go func(i, j int) {
defer wg.Done()
time.Sleep(time.Second)
fmt.Println(i, j)
}(i, j)
}
wg.Wait()
}
fmt.Println("Done")
}
package main
import (
"fmt"
"sync"
)
func main() {
var once sync.Once
once.Do(
func() {
fmt.Println(1)
},
)
once.Do(
func() {
fmt.Println(2)
},
)
fmt.Println("Done")
}
/*
1
Done
*/
package main
import (
"fmt"
"sync"
)
func main() {
var once sync.Once
go func() {
once.Do(
func() {
fmt.Println(1)
},
)
}()
go func() {
once.Do(
func() {
fmt.Println(2)
},
)
}()
fmt.Println("Done")
}
/*
Done
*/
package main
import (
"fmt"
"sync"
"time"
)
func main() {
var once sync.Once
go func() {
// 会阻塞
once.Do(
func() {
fmt.Println(2)
},
)
fmt.Println(2, "done")
}()
once.Do(
func() {
time.Sleep(time.Second * 3)
fmt.Println(1)
},
)
fmt.Println("Done")
time.Sleep(time.Second * 5)
}
/*
1
Done
2 done
*/