php小编柚子在这篇文章中将向大家介绍如何通过对通道进行多次写入来理解 golang 阻塞通道的行为。在golang中,通道是一种用于在协程之间传递数据的重要机制。当通道已满时,写入操作会被阻塞,直到通道有空闲位置。我们将通过一个简单的示例来演示这种行为,并解释阻塞通道的原理和使用方法。无论是初学者还是有经验的golang开发者,都能从本文中获得有益的知识和实践经验。让我们开始吧!
问题内容
我是 golang 新手,正在尝试了解该语言中的并发性。我有一个代码,可以将一些值推送到通道,然后读取它们。
package main import ( "log" "time" ) func Greet2(c chan string) { // logging to Stdout is not an atomic operation // so artificially, sleep for some time time.Sleep(2 * time.Second) // 5. until below line reads and unblock the channel log.Printf("5. Read Greet2:: %s\n\n", <-c) } func Greet(c chan string) { // 4. Push a new value to the channel, this will block // Process will look for other go routines to execute log.Printf("4. Add 'Greet::John' to the channel, block until it is read. Remember, 'Greet' goroutine will block and only other goroutines can run even though this go routine can pull the value out from the channel.\n\n") c <- "Greet::John!" // 8. This statement will never execute log.Printf("8. Read Greet:: %s !\n\n", <-c) } func main() { c := make(chan string) log.Println("1. Main start") // 2. Both go routine will be declared and both will // for a value to be inserted in the channel log.Println("2. Declare go routines.\n\n") go Greet(c) go Greet2(c) // 3. write will block log.Println("3. Add 'main::Hello' to the channel, block until it is read. Remember, 'main' goroutine will block and only other goroutines can run even though this go routine can pull the value out from the channel.\n\n") c <- "main::Hello" // Sleep to give time goroutines to execute time.Sleep(time.Second) // 6. read the channel value. log.Printf("6. Read main:: %s \n\n", <-c) // 7. Insert a new value to the channel log.Println("7. Add 'main::Bye' to the channel, block until it is read.\n") c <- "main::Bye" // Sleep to give time goroutines to execute time.Sleep(time.Second) log.Println("9. Main stop") }
上述程序的输出是
2023/09/02 21:58:07 1. Main start 2023/09/02 21:58:07 2. Declare go routines. 2023/09/02 21:58:07 3. Add 'main::Hello' to the channel, block until it is read. Remember, 'main' goroutine will block and only other goroutines can run even though this go routine can pull the value out from the channel. 2023/09/02 21:58:07 4. Add 'Greet::John' to the channel, block until it is read. Remember, 'Greet' goroutine will block and only other goroutines can run even though this go routine can pull the value out from the channel. 2023/09/02 21:58:10 5. Read Greet2:: main::Hello 2023/09/02 21:58:11 6. Read main:: Greet::John! 2023/09/02 21:58:11 7. Add 'main::Bye' to the channel, block until it is read. 2023/09/02 21:58:11 8. Read Greet:: main::Bye ! 2023/09/02 21:58:12 9. Main stop
我无法理解为什么 4.
(另一个写入通道)在 5.
(第一次从通道读取)之前执行,因为 3.
将阻塞,并且在读取值之前通道不可用来自它(在步骤 5.
中)。我是否误解了阻塞行为,在步骤 3.
中,只有 main
goroutine 块和 Greet
(在步骤 4.
中)可以向通道写入附加值?一个解释确实可以解决我的困惑:)
干杯, DD。
感谢您的回复,我已经创建了一个更简单的程序来演示。并发
package main import ( "fmt" ) func do2(c chan int) { fmt.Println(<-c) } func do(c chan int) { // 4. this statement is trying to write another value "2" to the channel // Channel already contains "1" as the value which has not been read yet. // this statement will wait for "1" to get read and block the execution. // Scheduler will look for other goroutines that can execute. // However, this("do") is blocked as well as "main" is blocked too and // there are no other goroutines to execute. // Hence, will result in a "Deadlock" fatal error. c <- 2 fmt.Println(<-c) } func main() { // 1. Declare a channel c := make(chan int) // 2. Declare "do" goroutine go do(c) // 3. write "1" to the channel // This will block and wait for program's other goroutines to read the value. // however, there is only "do" goroutine is defined can run at this point. // Scheduler, will try to run "do" goroutine. c <- 1 go do2(c) }
死锁
可以通过交换c 和<code>go do2(c)
语句来修复。死锁
可以通过交换c 和<code>go do2(c)
语句来修复。
解决方法
在 Go 中,当您在通道上发送值时(步骤 3 中的 c ),发送 Goroutine 将阻塞,直到有另一个 Goroutine 准备好从通道接收值。然而,这并不意味着没有其他 goroutine 可以继续执行。在您的代码中, <code>Greet
和 Greet2
c ),发送 Goroutine 将阻塞,直到有另一个 Goroutine 准备好从通道接收值。然而,这并不意味着没有其他 goroutine 可以继续执行。在您的代码中, <ol> 协程都在等待来自通道的值,因此当您在步骤 3 中发送值时,其中一个(不保证是哪一个)将解除阻塞并继续执行。<li>
<code>c
让我一步步分解事件的顺序:
Greet
和 Greet2
主程序启动,您创建一个频道 Greet
或 Greet2
您声明了两个 goroutine,Greet
解除阻塞并继续执行。它记录消息“4. 将‘Greet::John’添加到频道...”并发送“Greet::John!”在频道上。这会再次阻塞 Greet
您在通道上发送一个值“main::Hello”,这会阻塞主 goroutine,直到其他 goroutine 从通道读取数据。但是,两个 Goroutine 之一(Greet2
Greet
在向通道写入时仍被阻止,而 Greet2
Greet
Main 在通道上发送另一个值“main::Bye”。此时, 仍然在写入时被阻止,因此它永远不会记录“8. Read Greet:: main::Bye !”Greet2
碰巧首先被解锁,但也可能是 Greet
🎜因此,理解此处行为的关键是,当您在通道上发送值时,它会解锁任何正在等待从通道读取数据的 goroutine。等待的 goroutine 解除阻塞的顺序是不确定的,取决于调度程序。在您的情况下,🎜 碰巧首先被解锁,但也可能是 🎜。🎜 🎜总之,您观察到的行为与 Go 通道的工作方式完全一致,并且需要注意的是,竞争 Goroutines 之间的执行顺序无法保证。🎜
以上是通过对通道进行多次写入来理解 golang 阻塞通道行为的详细内容。更多信息请关注PHP中文网其他相关文章!

Golang更适合高并发任务,而Python在灵活性上更有优势。1.Golang通过goroutine和channel高效处理并发。2.Python依赖threading和asyncio,受GIL影响,但提供多种并发方式。选择应基于具体需求。

Golang和C 在性能上的差异主要体现在内存管理、编译优化和运行时效率等方面。1)Golang的垃圾回收机制方便但可能影响性能,2)C 的手动内存管理和编译器优化在递归计算中表现更为高效。

selectgolangforhighpperformanceandcorrency,ifealforBackendServicesSandNetwork程序; selectpypypythonforrapiddevelopment,dataScience和machinelearningDuetoitsverserverserverserversator versator anderticality andextility andextentensivelibraries。

Golang和Python各有优势:Golang适合高性能和并发编程,Python适用于数据科学和Web开发。 Golang以其并发模型和高效性能着称,Python则以简洁语法和丰富库生态系统着称。

Golang和Python分别在哪些方面更易用和学习曲线更平缓?Golang更适合高并发和高性能需求,学习曲线对有C语言背景的开发者较平缓。Python更适合数据科学和快速原型设计,学习曲线对初学者非常平缓。

Golang和C 在性能竞赛中的表现各有优势:1)Golang适合高并发和快速开发,2)C 提供更高性能和细粒度控制。选择应基于项目需求和团队技术栈。

Golang适合快速开发和并发编程,而C 更适合需要极致性能和底层控制的项目。1)Golang的并发模型通过goroutine和channel简化并发编程。2)C 的模板编程提供泛型代码和性能优化。3)Golang的垃圾回收方便但可能影响性能,C 的内存管理复杂但控制精细。

GoimpactsdevelopmentPositationalityThroughSpeed,效率和模拟性。1)速度:gocompilesquicklyandrunseff,ifealforlargeprojects.2)效率:效率:ITScomprehenSevestAndArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdEcceSteral Depentencies,增强开发的简单性:3)SimpleflovelmentIcties:3)简单性。


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

SublimeText3 英文版
推荐:为Win版本,支持代码提示!

SecLists
SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

适用于 Eclipse 的 SAP NetWeaver 服务器适配器
将Eclipse与SAP NetWeaver应用服务器集成。

VSCode Windows 64位 下载
微软推出的免费、功能强大的一款IDE编辑器

EditPlus 中文破解版
体积小,语法高亮,不支持代码提示功能