golang goroutine 同步操作
package main
import (
"fmt"
"sync"
"time"
)
func worker(i int, wg *sync.WaitGroup) {
fmt.Printf("sync worker %d starting\n", i)
time.Sleep(time.Second)
fmt.Printf("sync worker %d done\n", i)
defer wg.Done()
}
// sync.WaitGroup
func SyncWaitGroup() {
var wg sync.WaitGroup
fmt.Println("this is SyncWaitGroup func")
for i := 1; i <= 10; i++ {
// 创建10个 goroutine
wg.Add(1)
go worker(i, &wg)
}
wg.Wait()
}
package main
import (
"fmt"
"time"
)
func chanWorker(i int, done chan int) {
fmt.Printf("chan worker %d starting\n", i)
time.Sleep(time.Second)
fmt.Printf("chan worker %d done\n", i)
done <- i
}
// chan
func Channel() {
c := make(chan int)
fmt.Println("this is Channel func")
for i := 1; i <= 10; i++ {
// 创建10个 goroutine
go chanWorker(i, c)
}
<-c
}