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 的并发特别方便,成本也比开辟线程要低,那么同样的也会更容易的带来死锁问题。

相关推荐
后端漫漫20 小时前
Redis 客户端工具体系
数据库·redis·缓存
布吉岛的石头21 小时前
微服务网关统一鉴权、限流、日志实战
java·spring·微服务
研究点啥好呢21 小时前
字节跳动Go后端开发工程师面试题精选:10道高频考题+答案解析
面试·golang·php·求职招聘
追梦开发者1 天前
Redis 避坑指南①:从安装到连接,这 9 个坑 90% 的人都踩过
redis·缓存·database
wxin_VXbishe1 天前
springboot新能源车充电站管理系统小程序-计算机毕业设计源码29213
java·c++·spring boot·python·spring·django·php
代码漫谈1 天前
一文学习 SpringBoot 的 application.yml 配置,基于 Spring Boot 3.2.x
java·spring boot·spring·配置文件
2301_771717211 天前
最近在刷牛客:使用Spring AOP实现性能监控时
java·后端·spring
手握风云-1 天前
Spring AI:让大模型住进 Spring 生态(四)
java·后端·spring
敖正炀1 天前
boot-boost 项目架构设计文档
spring boot·spring