Golang学习笔记13:并发编程之缓冲channel
缓冲channel
定义:
c := make(chan int,n)         n是缓冲区大小
之前c := make(chan int)       相当于     c := make(chan int , 0)
往里写就阻塞。
例如:
//缓冲channel
package main
import (
    "fmt"
    "time"
)
var ch chan int
func test_channel(){
    ch := make(chan int)    //相当于make(chan int , 0)
    ch <- 1
    fmt.Println("come to end goroutine 1")
}
func main(){
    
    go test_channel()
    time.Sleep(2 * time.Second)
    fmt.Println("running end!")
    //<-ch
    
    //time.Sleep(time.Second)
}输出结果:
running end!结果显示:test_channel函数中的come to end goroutine 1无法打印,
原因:channel 容量为0,所以阻塞在ch <- 1 ,到main函数中等待两秒后,运行main函数中的打印命令。
进行读操作
package main
import (
    "fmt"
    "time"
)
var ch chan int
func test_channel(){
    ch := make(chan int)    //相当于make(chan int , 0)
    ch <- 1
    fmt.Println("come to end goroutine 1")
}
func main(){
    
    go test_channel()
    time.Sleep(2 * time.Second)
    fmt.Println("running end!")
    <-ch                         //读操作 , 只读不存到一个变量里
    
    time.Sleep(time.Second)
}以上函数,有了<-ch读操作之后,test_channel的写操作就不阻塞了,
以上流程就变成
main  -->  test_channel  -->  ch<-1写操作  -->  阻塞等待两秒  -->  打印main函数中的running end!  -->  <-ch读操作  -->  ch<-1写操作不再阻塞  -->  打印test_channel函数中的come to end goroutine 1  读完之后主函数结束的话,协程也是会结束的,所以读完后再睡一下。
但是按照上面读操作之后,整个程序会死锁,可能是Go版本更新笔记过时的原因,等之后专门看下channel缓冲的源码,找找原因
通过channel实现锁的功能。
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 赛 の 任意门!
 评论
ValineGitalk



