Golang Sync


golang goroutine 同步操作

sync.WaitGroup

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()
}

Channel

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
}

文章作者: 三空
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 三空 !
  目录