Channel 基本使用

简介: Channel 基本使用

channel


channel 是有类型的管道,可以用 channel 操作符 <- 对其发送或者接收值。

创建 channel


c := make(chan int)

注意:管道必须指定类型,比如这里是 int,即往管道里传送的数据只能是 int 类型。当然可以是 interface {} 这种空接口方式,这样就可以传送各种数据类型了

也可以用 var 来声明管道,但是好像没啥意义

package main
import "fmt"
func main() {
    var c chan int
    fmt.Printf("%T %v\n", c, c)
    d := make(chan int)
    fmt.Printf("%T %v\n", d, d)
}

输出

chan int <nil>
chan int 0xc42006e060

管道方向


ch <- v // Send v to channel ch. v := <-ch // Receive from ch, and // assign value to v.

“箭头” 就是数据流的方向

注意接受时候 <- 和 chan 变量之间没有空格,虽然有空格也不会报错,但是 ide 会提示,因此还是依照规范不空格比较好

基本使用


package main import "fmt" func foo(i int, c chan int) { c <- i fmt.Println("send:", i) } func main() { c := make(chan int) go foo(0, c) res := <-c fmt.Println("receive:", res) }

输出

send: 0
receive: 0

默认情况下,在另一端准备好之前,发送和接收都会阻塞。这使得 goroutine 可以在没有明确的锁或竞态变量的情况下进行同步。

发动和接收数据应当在并行线上,而不能是串行的,因为发送和接收都会阻塞,如果串行,就会死锁(就是一个一直阻塞在那等对端),但不用为此操心,因为 go 在执行时候(编译会通过)会报错,比如:

package main
func main() {
    c := make(chan int)
    c <- 0
    <-c
}

报错:

fatal error: all goroutines are asleep - deadlock!
相关文章
|
缓存 中间件 流计算
如何解决 Netty Channel.isWritable 返回 false
在 Netty 里,有4个方法用来查询 Channel 的状态:isOpen,isRegistered,isActive,isWritable,其中,isWritable 在并发量很高时会返回很多 false。 isWritable 是什么含义? isWritable:Returns true if and only if the I/O thread will perform the req
2858 0
如何解决 Netty Channel.isWritable 返回 false
|
8月前
|
Go
go之channel关闭与广播
go之channel关闭与广播
|
8月前
|
调度 PHP
Swoole 源码分析之 Channel 通道模块
通道,用于协程间通讯,支持多生产者协程和多消费者协程。底层自动实现了协程的切换和调度。通道与 PHP 的 Array 类似,仅占用内存,没有其他额外的资源申请,所有操作均为内存操作,无 IO 消耗。
122 5
Swoole 源码分析之 Channel 通道模块
|
9月前
|
传感器 JSON Dart
Dart笔记:stream_channel 包用法
Dart笔记:stream_channel 包用法
200 0
|
6月前
|
Go
在go中监听多个channel
在go中监听多个channel
|
8月前
|
存储 Go
Go 语言当中 CHANNEL 缓冲
Go 语言当中 CHANNEL 缓冲
|
9月前
|
消息中间件
.NET 中 Channel 类简单使用
`System.Threading.Channels` 提供异步生产者-消费者数据结构,用于.NET Standard上的跨平台同步。频道实现生产者/消费者模型,允许在任务间异步传递数据。简单示例展示如何创建无界和有界频道,以及多生产者和消费者共享频道的场景。频道常用于内存中的消息队列,通过控制生产者和消费者的速率来调整系统流量。
|
9月前
|
Go
Go-channel的妙用
Go-channel的妙用
67 0
|
存储 安全 Go
Golang通道(Channel)原理解析
Golang通道(Channel)原理解析
|
Cloud Native Java Go
这些 channel 用法你都用起来了吗?
这些 channel 用法你都用起来了吗?
118 0