[Go实战]go的goroutine和通道

52 阅读1分钟

1.goroutine并发模型

package main

import (
	"fmt"
	"testing"
	"time"
)

//并发模型
func TestMy(t *testing.T) {
	go DelayPrint() // 开启第一个goroutine
	go HelloWorld() // 开启第二个goroutine
	time.Sleep(2 * time.Second)
	fmt.Println("main function")
}

func HelloWorld() {
	fmt.Println("Hello world goroutine")
}

func DelayPrint() {
	for i := 1; i <= 4; i++ {
		time.Sleep(250 * time.Millisecond)
		fmt.Println(i)
	}
}

运行结果 

2.channel

package main

import (
	"fmt"
	"time"
)

func loop(ch chan int) {
	for {
		select {
		case i := <-ch:
			fmt.Println("this value of unbuffer channel", i)
		}
	}
}

func main() {
	//非缓冲 channel
	//error code 错误示范
	//errUnbufferedChannel()
	//true code 成功示范
	trueUnbufferedChannel()

	//缓冲 channel
	//error code 错误示范
	//errBufferedChannel()
	//true code 成功示范
	trueBufferedChannel()
}

func errUnbufferedChannel() {
	ch := make(chan int)
	ch <- 1
	go loop(ch)
	time.Sleep(1 * time.Millisecond)
	//这里会报错 fatal error: all goroutines are asleep - deadlock! 就是因为 ch<-1 发送了,但是同时没有接收者,所以就发生了阻塞
	//但如果我们把 ch <- 1 放到 go loop(ch) 下面,程序就会正常运行
}

func trueUnbufferedChannel() {
	ch := make(chan int)
	go loop(ch)
	ch <- 1
	time.Sleep(1 * time.Millisecond)
}

func errBufferedChannel() {
	ch := make(chan int, 3)
	ch <- 1
	ch <- 2
	ch <- 3
	ch <- 4
	go loop(ch)
	time.Sleep(1 * time.Millisecond)
	//这里也会报 fatal error: all goroutines are asleep - deadlock! ,这是因为 channel 的大小为 3 ,而我们要往里面塞 4 个数据,所以就会阻塞住
	//解决的办法有两个
	//把 channel 开大一点,这是最简单的方法,也是最暴力的
	//把 channel 的信息发送者 ch <- 1 这些代码移动到 go loop(ch) 下面 ,让 channel 实时消费就不会导致阻塞了
}

func trueBufferedChannel() {
	ch := make(chan int, 3)
	go loop(ch)
	ch <- 1
	ch <- 2
	ch <- 3
	ch <- 4
	time.Sleep(1 * time.Millisecond)
}

运行结果: