Golang基础——3

发布于 2022-05-22  0 次阅读


并发

目录结构

├─goroutine

│ └─goroutine.go

└─main.go

协程goroutine

main.go
______________________________________________________________________
package main

import (
	"fmt"
	"./goroutine"
	"runtime"
	"time"
)

func main() {
	//设置cpu的运行核心数
	runtime.GOMAXPROCS(1)
	
	//开启协程
	go goroutine.Loop()
	go goroutine.Loop()
	
	//防止主程序运行过快退出导致无打印结果
	time.Sleep(time.Second*2)
}

//0 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9
goroutine.go
______________________________________________________________________
package goroutine

import (
	"fmt"
	"time"
)

func Loop()  {
	for i:=0; i<10; i++ {
		time.Sleep(time.Microsecond*10)
		fmt.Println(i)
	}
}

多协程通信

main.go
______________________________________________________________________
package main

import (
	"fmt"
	"./goroutine"
	"runtime"
	"time"
)

func main() {
	go goroutine.Send()
	//go goroutine.Receive()
	go goroutine.ReceiveOut()
	time.Sleep(time.Second * 60)
}
goroutine.go
______________________________________________________________________
package goroutine

import (
	"fmt"
	"time"
)

//初始化chan
var chanInt chan int = make(chan int, 10)
var timeOut chan bool = make(chan bool)

//发送数据到chan
func Send() {
	//发送int数据
	chanInt <- 1
	time.Sleep(time.Second * 2)
	chanInt <- 2
	time.Sleep(time.Second * 2)
	chanInt <- 3
	time.Sleep(time.Second * 2)

	//发送timeout数据
	timeOut <- true
}

//从chan简单获取数据
func Receive(){
	num := <- chanInt
	fmt.Println(num)
	num = <- chanInt
	fmt.Println(num)
	num = <- chanInt
	fmt.Println(num)
}

//从chan接收数据|timeout
func ReceiveOut() {
	for{
		select {
		case num := <- chanInt :
			fmt.Println(num)
		//无论获取到什么数据
		case  <- timeOut :
			fmt.Println("timeout...")
		}
	}
}

多协程同步

sync.WaitGroup

main.go
______________________________________________________________________
package main

import (
	"fmt"
	"./goroutine"
	"runtime"
	"time"
)

func main() {
	goroutine.Read()
	go goroutine.Write()
	goroutine.WG.Wait()

	fmt.Println("Done")
	time.Sleep(time.Second * 60)
}

func main1() {
	runtime.GOMAXPROCS(1)
	wg := sync.WaitGroup{}
	wg.Add(20)
	for i := 0; i < 10; i++ {
		fmt.Println("A1: ", i)
		go func() {
			fmt.Println("A: ", i)
			wg.Done()
		}()
	}
	for i := 0; i < 10; i++ {
		fmt.Println("B1: ", i)
		go func(i int) {
			fmt.Println("B: ", i)
			wg.Done()
		}(i)
	}
	wg.Wait()
}
goroutine.go
______________________________________________________________________
package goroutine

//定义WG|大写,因为要在main里使用
var WG sync.WaitGroup

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

//读取
func Read(){
	for i:=0; i<3; i++ {
		WG.Add(1)
	}
}

//写入
func Write() {
	for i:=0; i<3; i++ {
		time.Sleep(time.Second*1)
		fmt.Println(i)
		WG.Done()
	}
}

君子慎独,不欺暗室。卑以自牧,含章可贞。
最后更新于 2022-05-22