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()
}
相关推荐
懒惰的bit9 天前
STM32F103C8T6 学习笔记摘要(四)
笔记·stm32·学习
zkyqss9 天前
OVS Faucet练习(下)
linux·笔记·openstack
Jay_5159 天前
C++ STL 模板详解:由浅入深掌握标准模板库
c++·学习·stl
冰茶_9 天前
ASP.NET Core API文档与测试实战指南
后端·学习·http·ui·c#·asp.net
丶Darling.9 天前
深度学习与神经网络 | 邱锡鹏 | 第五章学习笔记 卷积神经网络
深度学习·神经网络·学习
浦东新村轱天乐9 天前
【麻省理工】《how to speaking》笔记
笔记
奔跑的蜗牛AZ9 天前
TiDB 字符串行转列与 JSON 数据查询优化知识笔记
笔记·json·tidb
cwtlw9 天前
Excel学习03
笔记·学习·其他·excel
牛大了20239 天前
【LLM学习】2-简短学习BERT、GPT主流大模型
gpt·学习·bert
大模型铲屎官9 天前
【Go语言-Day 7】循环控制全解析:从 for 基础到 for-range 遍历与高级控制
开发语言·人工智能·后端·golang·大模型·go语言·循环控制