1. Home
  2. Docs
  3. golang
  4. goroutine和channel
  5. channel

channel

  • Q1: 什么是channel?
  • Q2: channel有什么特点?
  • Q3: 使用channel需要注意些什么?
  • Q4: 如何使用channel?
  • Q5: 如何配合select、range使用?
  • Q6: channel底层如何实现的?

什么是channel?

channel是GO中的一个核心类型, 可以看成一个管道, 用于gorutine之间的数据通讯

将通道视为一种信号机制将使您能够编写具有明确定义和更精确行为的更好的代码

channel有什么特点属性?

  • Guarantee Of Delivery
  • State
  • With or Without Data
  • channel分为有缓冲和无缓冲两种
  • channel是发送和接收, 而不要说读/写 因为channel不执行I/O

有/无缓冲是否确保收到

unbuffered Buffered
Delivery Guaranteed Not Guaranteed

用数据发送信号保证类型有三个配置可选

Guaranteed Not Guaranteed Delayed Guarantee
Channel unbuffered Buffered > 1 Buffered = 1

不同阶段的状态

NIL Open Closed
Send Blocked Allowed Panic
Receive Blocked Allowed Allowed

如何使用channel?

create channel

ch := make(chan int) 无缓冲(本质是保证同步)

ch := make(chan int, 10) 有缓冲

send channel

ch <- 2

receive channel

res := <-ch

如何配合select、range使用?

package main

import (
    "fmt"
)

func main() {
    const cap = 5
    ch := make(chan string, cap)

    go func() {
        // range 用于接收消息
        for p := range ch {
            fmt.Println("接收: ", p)
        }
    }()

    const work = 20

    for w := 0; w < work; w++ {
        select {
            case ch <- "paper":
                    fmt.Println("manager: send ack")
            default:
                    fmt.Println("manager: drop")
        }
    }

    close(ch)
}

相关资料

01-the-behavior-of-channels

02-Go: Buffered and Unbuffered Channels

03-The Nature Of Channels In Go

04-My Channel Select Bug

05-图解Go的channel底层实现

Was this article helpful to you? Yes No

How can we help?