Golang学习笔记_26——通道

Golang学习笔记_23------error补充
Golang学习笔记_24------泛型
Golang学习笔记_25------协程Golang学习笔记_25------协程


文章目录

    • 通道
      • [1. 创建通道](#1. 创建通道)
      • [2. 发送和接收数据](#2. 发送和接收数据)
      • [3. 带缓冲的通道](#3. 带缓冲的通道)
      • [4. Demo](#4. Demo)
    • 源码

通道

在Go中,协程是通过go关键字来创建的。当你使用go关键字调用一个函数时,该函数会在一个新的协程中执行。

协程的调度由Go运行时(runtime)管理,开发者不需要关心具体的调度细节。

虽然协程可以并发执行,但有时候我们需要在协程之间传递数据或进行同步。在Go中,这是通过通道(Channel)来实现的。

通道是一种类型安全的、多路复用的、在协程之间传递通信的管道。

通道的类型由通道中传递的元素类型决定。例如,chan int是一个可以传递int类型数据的通道。

1. 创建通道

使用make函数创建通道

go 复制代码
ch := make(chan int)

2. 发送和接收数据

使用箭头操作符(<-)向通道发送或接收数据

go 复制代码
ch <- 42 // 发送数据到通道
value := <- ch  // 从通道中接受数据

3. 带缓冲的通道

go 复制代码
// 创建一个缓冲区大小为2的缓冲通道
ch := make(chan int, 1)

4. Demo

go 复制代码
import "fmt"

func sum(a []int, c chan int) {
	total := 0

	for _, v := range a {
		total += v
	}
	c <- total // 将计算结果发送到通道

}

func channelDemo() {
	a := []int{7, 2, 8, -9, 4, 0}
	c := make(chan int)
	go sum(a[:len(a)/2], c)
	go sum(a[len(a)/2:], c)

	result1 := <-c
	result2 := <-c
	fmt.Println(result1 + result2)
}

测试方法

go 复制代码
func Test_channelDemo(t *testing.T) {
	channelDemo()
}

输出结果

复制代码
=== RUN   Test_channelDemo
12
--- PASS: Test_channelDemo (0.00s)
PASS

源码

go 复制代码
// channel_demo.go 文件
package channel_demo

import "fmt"

func sum(a []int, c chan int) {
	total := 0

	for _, v := range a {
		total += v
	}
	c <- total // 将计算结果发送到通道

}

func channelDemo() {
	a := []int{7, 2, 8, -9, 4, 0}
	c := make(chan int)
	go sum(a[:len(a)/2], c)
	go sum(a[len(a)/2:], c)

	result1 := <-c
	result2 := <-c
	fmt.Println(result1 + result2)
}
go 复制代码
// channel_demo_test.go 文件
package channel_demo

import "testing"

func Test_channelDemo(t *testing.T) {
	channelDemo()
}
相关推荐
Hacker_Z&Q31 分钟前
CSS 笔记2 (属性)
前端·css·笔记
丝斯20111 小时前
AI学习笔记整理(67)——大模型的Benchmark(基准测试)
人工智能·笔记·学习
whale fall1 小时前
2026 年 1-3 月雅思口语完整话题清单(1-4 月通用最终版)
笔记·学习
xian_wwq1 小时前
【学习笔记】对网络安全“三化六防挂图作战”的理解与思考
笔记·学习·三化六防
三伏5222 小时前
Cortex-M3权威指南Cn第十章——笔记
笔记·单片机·嵌入式硬件·cortex-m3
AI视觉网奇2 小时前
metahuman 购买安装记录
笔记·学习·ue5
koo3642 小时前
pytorch深度学习笔记19
pytorch·笔记·深度学习
历程里程碑2 小时前
Linux 17 程序地址空间
linux·运维·服务器·开发语言·数据结构·笔记·排序算法
winfreedoms3 小时前
java-网络编程——黑马程序员学习笔记
java·网络·学习
五VV3 小时前
【ESP32】SP3手柄与ESP32连接不上问题解决
经验分享·学习