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 天前
每日八股——Redis(1)
数据库·经验分享·redis·后端·缓存
N***H4861 天前
springcloud springboot nacos版本对应
spring boot·spring·spring cloud
on the way 1231 天前
day06-SpringDI 依赖注入
java·spring
C***11501 天前
Spring aop 五种通知类型
java·前端·spring
代码N年归来仍是新手村成员1 天前
【Java转Go】即时通信系统代码分析(一)基础Server 构建
java·开发语言·golang
至善迎风1 天前
Redis完全指南:从诞生到实战
数据库·redis·缓存
M***Z2101 天前
springboot中配置logback-spring.xml
spring boot·spring·logback
oMcLin1 天前
如何在 Debian 10 上配置并优化 Redis 集群,确保低延迟高并发的实时数据缓存与查询
redis·缓存·debian
DICOM医学影像1 天前
2. go语言从零实现以太坊客户端-查询区块链账户余额
开发语言·golang·区块链·以太坊·web3.0·hardhat
xiaolyuh1231 天前
Spring 事务核心原理 深度解析
java·数据库·spring