”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 过于简化的 Golang 通道!

过于简化的 Golang 通道!

发布于2024-08-21
浏览:954

Oversimplified Golang Channel!

TL;DR

The article explains Go channels, which enable safe communication between goroutines. It covers how to create, send, and receive data through channels, distinguishing between unbuffered and buffered types. It emphasizes the importance of closing channels to prevent deadlocks and improve resource management. Finally, it introduces the select statement for managing multiple channel operations efficiently.


Table of Contents

  1. Introduction to Go Channels
  2. Creating a Channel
  3. Sending Data
  4. Receiving Data
  5. Channel Types in Go
    • Unbuffered Channels
    • Buffered Channels
  6. Closing a Channel
    • Why Close Channels?
  7. Code Snippet Without Closing the Channel
    • Expected Output and Error
  8. Code Snippet With Closing the Channel
    • Expected Output
  9. Using the select Statement
    • Example of select with Channels
  10. FAQ on select
  11. Ensuring Messages from Both Channels Using WaitGroup
    • Example of using WaitGroup
  12. Conclusion

Introduction to Go Channels

Go, or Golang, is a powerful programming language designed for simplicity and efficiency. One of its standout features is the concept of channels, which facilitate communication between goroutines. Channels allow for safe data exchange and synchronization, making concurrent programming easier and more manageable.

In this article, we will explore channels in Go, breaking down their creation, data transmission, and reception. This will help you understand how to leverage channels effectively in your applications.

Creating a Channel

To create a channel in Go, you use the make function. Here's a simple code snippet demonstrating how to create a channel:

package main

import "fmt"

func main() {
    // Create a channel of type int
    ch := make(chan int)
    fmt.Println("Channel created:", ch)
}

In this example, we create a channel ch that can send and receive integers. The channel is unbuffered by default, meaning that it will block until both the sender and receiver are ready.

When you run the provided Go code, the output will look something like this:

Channel created: 0xc000102060

Explanation

  1. Channel Creation:

    • The line ch := make(chan int) creates a new channel of type int. This channel can be used to send and receive integer values.
  2. Channel Address:

    • The output 0xc000102060 is the memory address of the channel. In Go, when you print a channel, it displays its internal representation, which includes its address in memory.
    • This address indicates where the channel is stored in memory, but it doesn't provide any information about the channel's state or contents.

Sending Data

Once a channel is created, you can send data into it using the

go func() {
    ch 



In this snippet, we start a new goroutine that sends the integer value 42 into the channel ch. This asynchronous operation allows the main program to continue executing while the value is sent.

Receiving Data

To receive data from a channel, you also use the

value := 



In this example, we read from the channel ch and store the received value in the variable value. The program will block at this line until a value is available to read.

Channel Types in Go

In Go, channels can be categorized primarily into two types: unbuffered and buffered channels. Understanding these types is essential for effective concurrent programming.

1. Unbuffered Channels

An unbuffered channel is the simplest type. It does not have any capacity to hold data; it requires both the sender and receiver to be ready at the same time.

Characteristics:

  • Blocking Behavior: Sending and receiving operations block until both parties are ready. This ensures synchronization between goroutines.
  • Use Case: Best for scenarios where you want strict synchronization or when the communication is infrequent.

Example:

ch := make(chan int) // Unbuffered channel
go func() {
    ch 



2. Buffered Channels

Buffered channels allow you to specify a capacity, meaning they can hold a limited number of values before blocking sends.

Characteristics:

  • Non-blocking Sends: A send operation only blocks when the buffer is full. This allows for greater flexibility and can improve performance in certain scenarios.
  • Use Case: Useful when you want to decouple the sender and receiver, allowing the sender to continue executing until the buffer is filled.

Example:

ch := make(chan int, 2) // Buffered channel with capacity of 2
ch 



What is Closing a Channel?

In Go, closing a channel is an operation that signals that no more values will be sent on that channel. This is done using the close(channel) function. Once a channel is closed, it cannot be reopened or sent to again.

Why Do We Need to Close Channels?

  1. Signal Completion: Closing a channel indicates to the receiving goroutine that no more values will be sent. This allows the receiver to know when to stop waiting for new messages.

  2. Preventing Deadlocks: If a goroutine is reading from a channel that is never closed, it can lead to deadlocks where the program hangs indefinitely, waiting for more data that will never arrive.

  3. Resource Management: Closing channels helps in managing resources effectively, as it allows the garbage collector to reclaim memory associated with the channel once it is no longer in use.

  4. Iteration Control: When using a for range loop to read from a channel, closing the channel provides a clean way to exit the loop once all messages have been processed.

In this section, we will explore a Go code snippet that demonstrates the use of unbuffered channels. We will analyze the behavior of the code with and without closing the channel, as well as the implications of each approach.

Code Snippet Without Closing the Channel

Here’s the original code snippet without the close statement:

package main

import (
    "fmt"
)

func main() {
    messages := make(chan string)

    go func() {
        messages 



Expected Output and Error

fatal error: all goroutines are asleep - deadlock!

When you run this code, it will compile and execute, but it will hang indefinitely without producing the expected output. The reason is that the for msg := range messages loop continues to wait for more messages, and since the channel is never closed, the loop has no way of knowing when to terminate. This results in a deadlock situation, causing the program to hang.

Code Snippet With Closing the Channel

Now, let’s add the close statement back into the code:

package main

import (
    "fmt"
)

func main() {
    messages := make(chan string)

    go func() {
        messages 



Expected Output

With the close statement included, the output of this code will be:

Message 1
Message 2
Message 3

Explanation of Closure Behavior

In this version of the code:

  • The close(messages) statement signals that no more messages will be sent on the messages channel.
  • The for msg := range messages loop can now terminate gracefully once all messages have been received.
  • Closing the channel allows the range loop to exit after processing all messages, preventing any deadlock situation.

Again, what if you don't close the channel?

Let's imagine a scenario where channels in Go are like people in a conversation.


Scene: A Coffee Shop

Characters:

  • Alice: Always eager to share ideas.
  • Bob: Takes a long time to respond.

Conversation:

Alice: "Hey Bob, did you hear about the new project? We need to brainstorm!"

Bob sips his coffee, staring blankly. The conversation is paused.

Alice: "Hello? Are you there?"

Bob looks up, still processing.

Bob: "Oh, sorry! I was... uh... thinking."

Minutes pass. Alice starts to wonder if Bob is even still in the chat.

Alice: "Should I keep talking or just wait for a signal?"

Bob finally responds, but it’s completely off-topic.

Bob: "Did you know that sloths can hold their breath longer than dolphins?"

Alice facepalms.

Alice: "Great, but what about the project?"

Bob shrugs, lost in thought again. The coffee shop becomes awkwardly silent.

Alice: "Is this conversation ever going to close, or will I just be here forever?"

Bob, now fascinated by the barista, mutters something about coffee beans.

Alice: "This is like a Go channel that never gets closed! I feel like I’m stuck in an infinite loop!"

Bob finally looks back, grinning.

Bob: "So... about those sloths?"


Moral of the Story: Sometimes, when channels (or conversations) don’t close, you end up with endless topics and no resolution—just like a chat that drags on forever without a conclusion!

Go Channels and the select Statement

Go's concurrency model is built around goroutines and channels, which facilitate communication between concurrent processes. The select statement is vital for managing multiple channel operations effectively.

Using select with Channels

Here's an example of using select with channels:

package main

import (
    "fmt"
    "time"
)

func main() {
    ch1 := make(chan string)
    ch2 := make(chan string)

    go func() {
        time.Sleep(1 * time.Second)
        ch1 



Output with select:

Result from channel 1

Why Does It Print Only One Output?

In Go, the select statement is a powerful construct used for handling multiple channel operations. When working with channels, you might wonder why a program prints only one output when multiple channels are involved. Let’s explore this concept through a simple example.

Scenario Overview

Consider the program that involves two channels: ch1 and ch2. Each channel receives a message after a delay, but only one message is printed at the end. You might ask, "Why does it only print one output?"

Timing and Concurrency

  1. Channel Initialization: Both ch1 and ch2 are created to handle string messages.

  2. Goroutines:

    • A goroutine sends a message to ch1 after a 1-second delay.
    • Another goroutine sends a message to ch2 after a 2-second delay.
  3. Select Statement: The select statement listens for messages from both channels. It blocks until one of the channels is ready to send a message.

Execution Flow

  • When the program runs, it waits for either ch1 or ch2 to send a message.
  • After 1 second, ch1 is ready, allowing the select statement to execute the case for ch1.
  • Importantly, select can only execute one case at a time. Once a case is selected, it exits the select block.

FAQ on select

Q: Is it possible to wait for all channels in select to print all outputs?

A: No, the select statement is designed to handle one case at a time. To wait for multiple channels and print all outputs, you would need to use a loop or wait group.

Q: What happens if both channels are ready at the same time?

A: If both channels are ready simultaneously, Go will choose one at random to process, so the output may vary between executions.

Q: Can I handle timeouts with select?

A: Yes, you can include a timeout case in the select statement, allowing you to specify a duration to wait for a message.

Q: How can I ensure I receive messages from both channels?

A: To receive messages from both channels, consider using a loop with a select statement inside it, or use a sync.WaitGroup to wait for multiple goroutines to complete their tasks.

Ensuring Messages from Both Channels Using WaitGroup in Go

To ensure you receive messages from both channels in Go, you can use a sync.WaitGroup. This allows you to wait for multiple goroutines to complete before proceeding.

Here’s an example:

package main

import (
    "fmt"
    "sync"
    "time"
)

func main() {
    ch1 := make(chan string)
    ch2 := make(chan string)
    var wg sync.WaitGroup

    // Start goroutine for channel 1
    wg.Add(1)
    go func() {
        defer wg.Done()
        time.Sleep(1 * time.Second)
        ch1 



Output

Result from channel 1
Result from channel 2

Explanation

  1. Channels and WaitGroup: Two channels, ch1 and ch2, are created. A sync.WaitGroup is used to wait for both goroutines to finish.

  2. Goroutines: Each goroutine sends a message to its channel after a delay. The wg.Done() is called to signal completion.

  3. Closing Channels: After all goroutines are done, the channels are closed to prevent any further sends.

  4. Collecting Results: A loop with a select statement is used to receive messages from both channels until both messages are collected.

  5. Final Output: The collected messages are printed.

This method ensures that you wait for both channels to send their messages before proceeding.

If you're interested in learning more about using sync.WaitGroup in Go, check out this article on concurrency: Golang Concurrency: A Fun and Fast Ride.

Real world example

Let's compare the two versions of a program in terms of their structure, execution, and timing.

Sequential Execution Version

This version processes the jobs sequentially, one after the other.

package main

import (
    "fmt"
    "time"
)

func worker(id int, job int) string {
    time.Sleep(time.Second) // Simulate work
    return fmt.Sprintf("Worker %d completed job %d", id, job)
}

func main() {
    start := time.Now()
    results := make([]string, 5)

    for j := 1; j 



Output:

Worker 1 completed job 1
Worker 1 completed job 2
Worker 1 completed job 3
Worker 1 completed job 4
Worker 1 completed job 5
It took 5.048703s to execute!

Concurrent Execution Version

This version processes the jobs concurrently using goroutines and channels.

package main

import (
    "fmt"
    "time"
)

func worker(id int, jobs 



Output:

Worker 1 completed job 1
Worker 2 completed job 2
Worker 3 completed job 3
Worker 1 completed job 4
Worker 2 completed job 5
It took 2.0227664s to execute!

Comparison

Structure:

  • Sequential Version: Calls the worker function directly in a loop. No concurrency.
  • Concurrent Version: Uses goroutines to run multiple worker functions concurrently and channels for job distribution and result collection.

Execution:

  • Sequential Version: Each job is processed one after the other, taking 1 second per job, leading to a total execution time roughly equal to the number of jobs (5 seconds for 5 jobs).
  • Concurrent Version: Multiple workers (3 in this case) process jobs concurrently, reducing the total execution time significantly. Jobs are distributed among the workers, and results are collected via channels.

Timing:

  • Sequential Version: Took approximately 5.048703 seconds.
  • Concurrent Version: Took approximately 2.0227664 seconds.

The concurrent version is significantly faster because it leverages parallel execution, allowing multiple jobs to be processed simultaneously. This reduces the total execution time to around the time it takes to complete the longest job, divided by the number of workers, rather than summing up the time for each job as in the sequential version.

Official Documentation References

  1. Go Documentation - Goroutines

    Goroutines

  2. Go Documentation - Channels

    Channels

  3. Go Blog - Concurrency in Go

    Concurrency in Go

  4. Go Documentation - The select Statement

    Select Statement

  5. Go Tour - Channels

    Tour of Go: Channels

Conclusion

In summary, the article provides a clear and simplified overview of channels in Go, emphasizing their role in facilitating safe communication between goroutines. By explaining the concepts of unbuffered and buffered channels, the article highlights their distinct behaviors and appropriate use cases. Additionally, it underscores the importance of closing channels to prevent deadlocks and ensure efficient resource management. With practical code examples and relatable analogies, the article equips readers with a foundational understanding of how to effectively utilize channels in their Go applications, paving the way for more robust concurrent programming.

版本声明 本文转载于:https://dev.to/ashsajal/oversimplified-golang-channel-2e42?1如有侵犯,请联系[email protected]删除
最新教程 更多>
  • 如何使用 JSTL 迭代 HashMap 中的 ArrayList?
    如何使用 JSTL 迭代 HashMap 中的 ArrayList?
    使用 JSTL 迭代 HashMap 中的 ArrayList在 Web 开发中,JSTL(JavaServer Pages 标准标记库)提供了一组标记来简化 JSP 中的常见任务( Java 服务器页面)。其中一项任务是迭代数据结构。要迭代 HashMap 及其中包含的 ArrayList,可以使...
    编程 发布于2024-11-05
  • Encore.ts — 比 ElysiaJS 和 Hono 更快
    Encore.ts — 比 ElysiaJS 和 Hono 更快
    几个月前,我们发布了 Encore.ts — TypeScript 的开源后端框架。 由于已经有很多框架,我们想分享我们做出的一些不常见的设计决策以及它们如何带来卓越的性能数据。 性能基准 我们之前发布的基准测试显示 Encore.ts 比 Express 快 9 倍,比 Fasti...
    编程 发布于2024-11-05
  • 为什么使用 + 对字符串文字进行字符串连接失败?
    为什么使用 + 对字符串文字进行字符串连接失败?
    连接字符串文字与字符串在 C 中,运算符可用于连接字符串和字符串文字。但是,此功能存在限制,可能会导致混乱。在问题中,作者尝试连接字符串文字“Hello”、“,world”和“!”以两种不同的方式。第一个例子:const string hello = "Hello"; const...
    编程 发布于2024-11-05
  • React 重新渲染:最佳性能的最佳实践
    React 重新渲染:最佳性能的最佳实践
    React高效的渲染机制是其受欢迎的关键原因之一。然而,随着应用程序复杂性的增加,管理组件重新渲染对于优化性能变得至关重要。让我们探索优化 React 渲染行为并避免不必要的重新渲染的最佳实践。 1. 使用 React.memo() 作为函数式组件 React.memo() 是一个高...
    编程 发布于2024-11-05
  • 如何实现条件列创建:探索 Pandas DataFrame 中的 If-Elif-Else?
    如何实现条件列创建:探索 Pandas DataFrame 中的 If-Elif-Else?
    Creating a Conditional Column: If-Elif-Else in Pandas给定的问题要求将新列添加到 DataFrame 中基于一系列条件标准。挑战在于在实现这些条件的同时保持代码效率和可读性。使用函数应用程序的解决方案一种方法涉及创建一个将每一行映射到所需结果的函数...
    编程 发布于2024-11-05
  • 介绍邱!
    介绍邱!
    我很高兴地宣布发布 Qiu – 一个严肃的 SQL 查询运行器,旨在让原始 SQL 再次变得有趣。老实说,ORM 有其用武之地,但当您只想编写简单的 SQL 时,它们可能会有点让人不知所措。我一直很喜欢编写原始 SQL 查询,但我意识到我需要练习——大量的练习。这就是Qiu发挥作用的地方。 有了 Q...
    编程 发布于2024-11-05
  • 为什么 CSS 中的 Margin-Top 百分比是根据容器宽度计算的?
    为什么 CSS 中的 Margin-Top 百分比是根据容器宽度计算的?
    CSS 中的 margin-top 百分比计算当对元素应用 margin-top 百分比时,必须了解计算方式执行。与普遍的看法相反,边距顶部百分比是根据包含块的宽度而不是其高度来确定的。W3C 规范解释:根据W3C 规范,“百分比是根据生成的框包含块的宽度计算的。”此规则适用于“margin-top...
    编程 发布于2024-11-05
  • 如何解决 CSS 转换期间 Webkit 文本渲染不一致的问题?
    如何解决 CSS 转换期间 Webkit 文本渲染不一致的问题?
    解决 CSS 转换期间的 Webkit 文本渲染不一致在 CSS 转换期间,特别是缩放元素时,Webkit 中可能会出现文本渲染不一致的情况浏览器。这个问题源于浏览器尝试优化渲染性能。一种解决方案是通过添加以下属性来强制对过渡元素的父元素进行硬件加速:-webkit-transform: trans...
    编程 发布于2024-11-05
  • 使用 Reactables 简化 RxJS
    使用 Reactables 简化 RxJS
    介绍 RxJS 是一个功能强大的库,但众所周知,它的学习曲线很陡峭。 该库庞大的 API 界面,再加上向反应式编程的范式转变,可能会让新手不知所措。 我创建了 Reactables API 来简化 RxJS 的使用并简化开发人员对反应式编程的介绍。 例子 我们将构建...
    编程 发布于2024-11-05
  • 如何在 Pandas 中查找多列的最大值?
    如何在 Pandas 中查找多列的最大值?
    查找 Pandas 中多列的最大值要确定 pandas DataFrame 中多列的最大值,可以采用多种方法。以下是实现此目的的方法:对指定列使用 max() 函数此方法涉及显式选择所需的列并应用 max() 函数: df[["A", "B"]] df[[&q...
    编程 发布于2024-11-05
  • CI/CD 入门:自动化第一个管道的初学者指南(使用 Jenkins)
    CI/CD 入门:自动化第一个管道的初学者指南(使用 Jenkins)
    目录 介绍 什么是 CI/CD? 持续集成(CI) 持续交付(CD) 持续部署 CI/CD 的好处 更快的上市时间 提高代码质量 高效协作 提高自动化程度和一致性 如何创建您的第一个 CI/CD 管道 第 1 步:设置版本控制 (GitHub) 第 2 步:选择 CI/CD 工具 ...
    编程 发布于2024-11-05
  • TypeScript 如何使 JavaScript 在大型项目中更加可靠。
    TypeScript 如何使 JavaScript 在大型项目中更加可靠。
    介绍 JavaScript 广泛应用于 Web 开发,现在也被应用于不同行业的大型项目中。然而,随着这些项目的增长,管理 JavaScript 代码变得更加困难。数据类型不匹配、运行时意外错误以及代码不清晰等问题可能会导致查找和修复错误变得困难。 这就是TypeScript介入的地...
    编程 发布于2024-11-05
  • 如何使用PHP的password_verify函数安全地验证用户密码?
    如何使用PHP的password_verify函数安全地验证用户密码?
    使用 PHP 解密加密密码许多应用程序使用密码哈希等加密算法安全地存储用户密码。然而,在验证登录尝试时,将输入密码与加密的存储版本进行比较非常重要。加密问题password_hash 使用 Bcrypt,一种一元加密算法方式哈希算法,意味着加密的密码无法逆转或解密。这是一项安全功能,可确保即使数据库...
    编程 发布于2024-11-05
  • 学习 Vue 部分 构建天气应用程序
    学习 Vue 部分 构建天气应用程序
    深入研究 Vue.js 就像在 DIY 工具包中发现了一个新的最喜欢的工具——直观、灵活,而且功能强大得惊人。我接触 Vue 的第一个副业项目是一个天气应用程序,它教会了我很多关于框架功能以及一般 Web 开发的知识。这是我到目前为止所学到的。 1. Vue 入门:简单与强大 Vue...
    编程 发布于2024-11-05
  • NFT 预览卡组件
    NFT 预览卡组件
    ?刚刚完成了我的最新项目:使用 HTML 和 CSS 的“NFT 预览卡组件”! ?查看并探索 GitHub 上的代码。欢迎反馈! ? GitHub:[https://github.com/khanimran17/NFT-preview-card-component] ?现场演示:[https://...
    编程 发布于2024-11-05

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3