脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Golang - golang channel管道使用示例解析

golang channel管道使用示例解析

2022-09-15 14:21Jeff的技术栈 Golang

这篇文章主要介绍了golang channel管道使用示例解析,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步早日升职加薪

定义channel管道

定义一个channel时,也需要定义发送到管道的值类型。channel可以使用内置的make()函数来创建:

?
1
2
var ch = make(chan int) //等价于:make(chan Type,0)
var ch = make(chan Type,capacity)

channel管道塞值和取值

?
1
2
3
4
ch <- 666  //向ch管道塞入666
<- ch  // 向ch管道接收值,并丢弃
x := <-ch  //向ch管道中接收数据,并复制给x
x, ok := <-ch  //向ch管道中接收数据,并复制给x,同时检查通道是否已关闭或者是否为空

当capacity=0时,channel管道是无缓冲阻塞读写,
当capacity>0时,channel管道有缓冲,是非阻塞的,直到写满capacity个元素才阻塞写入。
 

注意:默认情况下,channel接收和发送数据都是阻塞的,除非另一端已经准备好,这样就使得goroutine同步变得更加简单,而不需要显示的lock。

通过channel管道实现同步,和数据交互

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package main
import (
    "fmt"
    "time"
)
func main() {
    //创建channel
    ch := make(chan string)
    defer fmt.Println("主协程也结束")
    go func() {
        defer fmt.Println("子协程调用完毕")
        for i := 0; i < 2; i++ {
            fmt.Println("子协程 i = ", i)
            time.Sleep(time.Second)
        }
        ch <- "我是子协程,要工作完毕"
    }()
    str := <-ch //没有数据前,阻塞
    fmt.Println("str = ", str)
}

无缓冲的channel

ch := make(chan int, 0)

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package main
import (
    "fmt"
    "time"
)
func main() {
    //创建一个无缓存的channel
    ch := make(chan int, 0)
 
    //len(ch)缓冲区剩余数据个数, cap(ch)缓冲区大小
    fmt.Printf("len(ch) = %d, cap(ch)= %d\n", len(ch), cap(ch))
    //新建协程
    go func() {
        for i := 0; i < 10000; i++ {
            fmt.Printf("子协程:i = %d\n", i)
            ch <- i //往chan写内容
            time.Sleep(1 * time.Second)
        }
    }()
    go func() {
        for  {
            num := <-ch //读管道中内容,没有内容前,阻塞
            fmt.Println("num = ", num)
        }
 
    }()
    for {
    }
}

有缓冲的channel管道

ch := make(chan int, 3)

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package main
import (
    "fmt"
    "time"
)
func main() {
    //创建一个有缓存的channel
    ch := make(chan int, 3)
    //len(ch)缓冲区剩余数据个数, cap(ch)缓冲区大小
    fmt.Printf("len(ch) = %d, cap(ch)= %d\n", len(ch), cap(ch))
    //新建协程
    go func() {
        for i := 0; i < 10; i++ {
            ch <- i //往chan写内容
            fmt.Printf("子协程[%d]: len(ch) = %d, cap(ch)= %d\n", i, len(ch), cap(ch))
        }
    }()
    //延时
    time.Sleep(2 * time.Second)
    for i := 0; i < 10; i++ {
        num := <-ch //读管道中内容,没有内容前,阻塞
        fmt.Println("num = ", num)
    }
}

关闭channel管道

close(ch)

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package main
import (
    "fmt"
)
func main() {
    //创建一个无缓存的channel
    ch := make(chan int, 3)
    //len(ch)缓冲区剩余数据个数, cap(ch)缓冲区大小
    fmt.Printf("len(ch) = %d, cap(ch)= %d\n", len(ch), cap(ch))
    //新建协程
    go func() {
        for i := 0; i < 10000; i++ {
            fmt.Printf("子协程:i = %d\n", i)
            ch <- i //往chan写内容
            //time.Sleep(1 * time.Second)
            if i >10 {
                close(ch)
                break
            }
        }
    }()
    go func() {
        for  {
            if num, ok := <-ch; ok == true {
                fmt.Println("num = ", num)
            } else { //管道关闭
                break
            }
        }
    }()
    for {
 
    }
}

单向channel管道,读写分离

chan<-  表示数据进入管道,只写
<-chan 表示数据从管道出来,只读

注意:双向可转为单向,单向不可转为双向

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package main
//"fmt"
func main() {
    //创建一个channel, 双向的
    ch := make(chan int)
    //双向channel能隐式转换为单向channel
    var writeCh chan<- int = ch //只能写,不能读
    var readCh <-chan int = ch  //只能读,不能写
    writeCh <- 666 //写
    //<-writeCh //err,  invalid operation: <-writeCh (receive from send-only type chan<- int)
    <-readCh //读
    //readCh <- 666 //写, err,  invalid operation: readCh <- 666 (send to receive-only type <-chan int)
    //单向无法转换为双向
    //var ch3 chan int = writeCh //cannot use writeCh (type chan<- int) as type chan int in assignment
 
}

管道消费者生产者模型

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package main
import (
    "fmt"
)
//此通道只能写,不能读
func producer(out chan<- int) {
    for i := 0; i < 10; i++ {
        out <- i * i  //写入
    }
    close(out)  //关闭
}
//此channel只能读,不能写
func consumer(data <-chan int) {
    for num := range data {
        fmt.Println("num = ", num)
    }
}
func main() {
    //创建一个双向通道
    ch := make(chan int)
    //生产者,生产数字,写入channel
    //新开一个协程
    go producer(ch) //channel传参,引用传递
    //消费者,从channel读取内容,打印
    consumer(ch)
}

以上就是golang channel管道的详细内容,更多关于channel管道的资料请关注服务器之家其它相关文章!

原文链接:https://www.cnblogs.com/guyouyin123/p/13986351.html

延伸 · 阅读

精彩推荐
  • Golang详解golang 定时任务time.Sleep和time.Tick实现结果比较

    详解golang 定时任务time.Sleep和time.Tick实现结果比较

    本文主要介绍了golang 定时任务time.Sleep和time.Tick实现结果比较,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...

    alphaTao10252022-09-03
  • GolangGolang并发编程包之 Errgroup

    Golang并发编程包之 Errgroup

    Task 是需要处理单个工作单元;Worker 是一个简单的 worker 函数,用于执行任务;而 Pool 用于创建、管理 workers。...

    Golang来啦7682021-08-06
  • Golanggolang import自定义包方式

    golang import自定义包方式

    这篇文章主要介绍了golang import自定义包方式,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...

    loongshawn9862021-06-08
  • GolangGo 结构体序列化的实现

    Go 结构体序列化的实现

    本文主要介绍了Go 结构体序列化的实现,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...

    Go语言由浅入深5252022-08-31
  • GolangGolang 语言 gRPC 怎么使用?

    Golang 语言 gRPC 怎么使用?

    既然我们要介绍 gRPC 怎么在 Golang 语言中使用,那么我们必须搭建 Golang 开发环境。这部分内容比较简单,本文就不再赘述了,如果有读者朋友对这块内容不...

    Golang语言开发栈4872021-09-14
  • GolangGo语言中使用 buffered channel 实现线程安全的 pool

    Go语言中使用 buffered channel 实现线程安全的 pool

    这篇文章主要介绍了Go语言中使用 buffered channel 实现线程安全的 pool,因为Go语言自带的sync.Pool并不是很好用,所以自己实现了一线程安全的 pool,需要的朋友可...

    junjie4702020-04-09
  • GolangGo实现用户每日限额的方法(例一天只能领三次福利)

    Go实现用户每日限额的方法(例一天只能领三次福利)

    这篇文章主要介绍了Go实现用户每日限额的方法(例一天只能领三次福利)...

    万俊峰Kevin7922022-08-29
  • Golang详解Go语言中for range的"坑"

    详解Go语言中for range的"坑"

    这篇文章主要介绍了详解Go语言中for range的"坑",文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随...

    mokeyWie6642021-01-02