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

相关推荐
lambo mercy7 小时前
08_redis__集群 (Cluster)
数据库·redis·缓存
Doctor_Strange_DML8 小时前
图像编辑模型服务部署过程记录
linux·缓存·docker·ai
会编程的吕洞宾15 小时前
Spring Boot虚拟线程实战:吞吐提升3倍
java·经验分享·后端·spring
xurileidian16 小时前
第 22 篇 · 边玩边学Python · 双等号与 is 不是一回事
开发语言·python·spring
斑鸠喳喳19 小时前
Spring IoC 之 BeanFactoryPostProcessor
java·spring
NendoZen19 小时前
Bubble Tea V2构建Go TUI应用教程
开发语言·golang·xcode
always202220 小时前
AI运行时 · 附录4 - KVCache 卸载与推理运行时:PagedAttention / PD 分离 / 分层缓存的显存经济学
人工智能·缓存
pan_junbiao20 小时前
Go 语言变量的声明与初始化
开发语言·javascript·golang
pan_junbiao1 天前
Go 语言基本数据类型
java·前端·golang
codeejun1 天前
每日一Go·MySQL-24、死锁排查与解决方案
开发语言·mysql·golang