Golang 并发编程基础

runtime 包,定义了协程管理相关的 API

runtime.Gosched()

package main

import (
	"fmt"
	"runtime"
)

func main() {
	go func() {
		for i := 0; i <= 5; i++ {
			fmt.Println(i)
		}
	}()

	// 让出当前CPU给其他协程
	runtime.Gosched()
	fmt.Println("end...")
}

runtime.Goexit()

package main

import (
	"fmt"
	"runtime"
	"time"
)

func show() {
	for i := 0; i <= 5; i++ {
		if i > 3 {
			// 退出当前协程
			runtime.Goexit()
		}
		fmt.Println(i)
	}
}

func main() {
	go show()
	// 主协程睡眠1s
	time.Sleep(time.Second)
	fmt.Println("end...")
}

runtime.GOMAXPROCS()

package main

import (
	"fmt"
	"runtime"
	"time"
)

func funcA() {
	for i := 0; i < 5; i++ {
		fmt.Printf("funcA: %v \n", i)
		time.Sleep(time.Millisecond * 100)
	}
}

func funcB() {
	for i := 0; i < 5; i++ {
		fmt.Printf("funcB: %v \n", i)
		time.Sleep(time.Millisecond * 100)
	}
}

func main() {
	fmt.Printf("CPU nums: %v \n", runtime.NumCPU())

	// 设置最大CPU核心数
	runtime.GOMAXPROCS(1)
	go funcA()
	go funcB()

	// 主协程睡眠1s
	time.Sleep(time.Second)
	fmt.Println("end...")
}

Mutex 互斥锁实现同步

sync.Mutex

package main

import (
	"fmt"
	"sync"
	"time"
)

var count int
var wp sync.WaitGroup
var lock sync.Mutex

func add() {
	defer wp.Done()
	// 加锁
	lock.Lock()
	count++
	fmt.Printf("add: %v \n", count)
	time.Sleep(time.Millisecond * 10)
	// 解锁
	lock.Unlock()
}

func sub() {
	defer wp.Done()
	lock.Lock()
	count--
	fmt.Printf("sub: %v \n", count)
	time.Sleep(time.Millisecond * 100)
	lock.Unlock()
}

func main() {
	for i := 0; i < 10; i++ {
		wp.Add(1)
		go add()
		wp.Add(1)
		go sub()
	}

	// 等待子协程执行完再执行主协程
	wp.Wait()
	fmt.Printf("count: %v \n", count)
	fmt.Println("end...")
}

你可能感兴趣的:(Golang,golang)