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

相关推荐
麦兜*18 小时前
MongoDB Atlas 云数据库实战:从零搭建全球多节点集群
java·数据库·spring boot·mongodb·spring·spring cloud
麦兜*18 小时前
MongoDB 在物联网(IoT)中的应用:海量时序数据处理方案
java·数据库·spring boot·物联网·mongodb·spring
-Xie-18 小时前
Mysql杂志(十六)——缓存池
数据库·mysql·缓存
七夜zippoe18 小时前
缓存与数据库一致性实战手册:从故障修复到架构演进
数据库·缓存·架构
青衫客3619 小时前
Spring异步编程- 浅谈 Reactor 核心操作符
java·spring·响应式编程
weixin_4569042719 小时前
跨域(CORS)和缓存中间件(Redis)深度解析
redis·缓存·中间件
Cyan_RA91 天前
SpringMVC @RequestMapping的使用演示和细节 详解
java·开发语言·后端·spring·mvc·ssm·springmvc
MarkHard1231 天前
如何利用redis使用一个滑动窗口限流
数据库·redis·缓存
心想事成的幸运大王1 天前
Redis的过期策略
数据库·redis·缓存
o0o_-_1 天前
【go/gopls/mcp】官方gopls内置mcp server使用
开发语言·后端·golang