8

go基础之通道_zzxiaoma的技术博客_51CTO博客

 2 years ago
source link: https://blog.51cto.com/u_3764469/5569825
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

go基础之通道

原创

zzxiaoma 2022-08-12 08:35:41 博主文章分类:go ©著作权

文章标签 通道 文章分类 Go语言 编程语言 yyds干货盘点 阅读数155

通道是为了解决多个不同的goroutine之间的通信。通道带有类型的值,所以创建通道时,需要带上数据类型。

ch := make(chan int)

使用make创建一个由整数组成的通道,默认是无缓冲通道,当一个goroutine把信息放入无缓冲通道之后,除非有某个goroutine把这项信息取走,否则其他goroutine将无法再向这个通道放入任何信息,进入阻塞状态,直到通道变空为止。同样,如果一个goroutine尝试从一个并没有包含任何信息的无缓冲通道取信息时,进入阻塞状态,直到通道不再为空为止。

假如有这么一个需求,在2次print函数之后,还有个函数名字叫call(),这个call()函数需要在2次print函数执行后才能执行,这样如何写呢?

package main

import (
"fmt"
)

func print(c chan int) {
arr := [10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
for _, i := range arr {
fmt.Println(i)
}
c <- 1
}

func call() {
fmt.Println("call")
}

func main() {
c1 := make(chan int)
c2 := make(chan int)
go print(c1)
go print(c2)
<-c1
<-c2
call()
}
<-c1
<-c2

这2句会阻塞,直到能够从c1和c2通道获取数据才往下执行。

创建有缓冲通道ch := make(chan int,10),这样一个通道可以存放10个int,只有超过10个才会阻塞。

package main

import (
"fmt"
"time"
)

func showFunc (c chan string){
for msg := range c{
fmt.Println(msg)
}
}

func main(){
messages := make(chan string,2)
messages <- "hello"
messages <- "world"
close(messages)
fmt.Println("aaaa")
time.Sleep(time.Second * 1)
showFunc(messages)
}

先创建2个缓冲的通道,往通道存放2个字符串,循环获取通道中的所有消息。这里需要注意close(messages),说明通道关闭后还是可以从通道里面拿数据的。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK