go | chan 并发传输或者设置chan缓存|死锁

chan 在定义的时候设置缓存,或者定义一个协程,去获取chan 传输

如果不是这两种解决方案,会出现线程死锁问题

可以自行尝试

采用goroutine 并发执行

go 复制代码
//go 采用协程处理接受chan
package main

import (
	"fmt"
)

func main() {

	fmt.Println("Hello, 世界")

	// 创建一个整数类型的通道
	ch1 := make(chan int)
	ch2 := make(chan int)

	// 启动一个 Goroutine 并发地将通道 ch1 中的数据发送到通道 ch2 中
	go func() {
		tmp := <-ch1
		ch2 <- tmp
		fmt.Println("tmp ", tmp)
	}()

	// 向通道 ch1 发送数据
	ch1 <- 22

	// 从通道 ch2 中接收数据
	data := <-ch2

	// 打印接收到的数据
	fmt.Println("data:", data)

	fmt.Println("test end....")
}

输出结果

bash 复制代码
Hello, 世界
data: 22
test end....

设置chan 缓冲

go 复制代码
fmt.Println("Hello, 世界")

	// 创建一个整数类型的通道
	ch1 := make(chan int, 1)
	ch2 := make(chan int, 1)

	ch1 <- 22
	tmp := <-ch1
	// 从通道 ch2 中接收数据
	ch2 <- tmp
	tmp2 := <-ch2

	// 打印接收到的数据
	fmt.Println("tmp: ", tmp, "tmp2: ", tmp2)

	fmt.Println("test end....")

执行结果

bash 复制代码
Hello, 世界
tmp:  22 tmp2:  22
test end....

总结

go 的并发特别方便,成本也比开辟线程要低,那么同样的也会更容易的带来死锁问题。

相关推荐
蓝宝石的傻话1 小时前
因为MiBeeNVR,决定接 onvif-go 自己管理并重构
数码相机·重构·golang
garmin Chen1 小时前
redis面试题
java·数据库·redis·缓存
卓怡学长6 小时前
w175基于springboot校园二手物品交易平台
java·spring boot·spring·maven·intellij-idea
互联网中的一颗神经元7 小时前
09. mheap:全局堆管理器
java·spring·dubbo
ttwuai7 小时前
Go 后台管理系统组件库文档怎么写,才不会坑后续维护?
开发语言·javascript·golang
2601_962174177 小时前
Spring 核心技术解析【纯干货版】- XI:Spring 数据访问模块 Spring-Oxm 模块精讲
数据库·python·spring
2601_962122978 小时前
Spring Cloud——路由网关Zuul
后端·spring·spring cloud
2601_962066238 小时前
golang超详细基础入门教程_golang教程
前端·python·golang
程序员夏洛8 小时前
Redis 的 Red Lock 是什么?你了解吗?
数据库·redis·缓存
亚历克斯神17 小时前
低代码与 AI 的融合趋势——从可视化搭建到自然语言生成应用
java·spring·微服务