💻 Programming

Channel

Channel

A tool in Go for safe communication between goroutines. A core element of concurrent programming.

📖 Detailed Explanation

A channel is a communication mechanism in Go for safely exchanging data between goroutines. A core feature that embodies Go's philosophy of "Do not communicate by sharing memory; instead, share memory by communicating," it prevents the race conditions that can occur in concurrent programming.

A channel can be thought of as a typed pipeline. You create a channel that passes integers with make(chan int), send a value with ch <- value, and receive a value with value := <-ch. By default, channels operate synchronously, blocking until both the sender and the receiver are ready.

A buffered channel is created by specifying a capacity, as in make(chan int, 10). Until the buffer is full, the sender does not block, which enables asynchronous communication. This is useful for improving performance in the producer-consumer pattern.

The select statement lets you wait on multiple channel operations at once. This lets you elegantly implement complex concurrency patterns such as timeout handling, receiving data from multiple sources, and handling cancellation signals. The close() function closes a channel to signal that no more values will be sent.

💻 Code Example

package main

import (
    "fmt"
    "time"
)

// 작업자 함수 - 채널로 결과 전송
func worker(id int, jobs <-chan int, results chan<- int) {
    for job := range jobs {
        fmt.Printf("Worker %d processing job %d\n", id, job)
        time.Sleep(time.Millisecond * 100)
        results <- job * 2
    }
}

func main() {
    jobs := make(chan int, 5)
    results := make(chan int, 5)

    // 3개의 워커 고루틴 시작
    for w := 1; w <= 3; w++ {
        go worker(w, jobs, results)
    }

    // 5개의 작업 전송
    for j := 1; j <= 5; j++ {
        jobs <- j
    }
    close(jobs)

    // 결과 수집
    for r := 1; r <= 5; r++ {
        result := <-results
        fmt.Printf("Result: %d\n", result)
    }
}

🗣️ Examples of Practical Conversations

Senior: The part that fetches data from multiple APIs is too slow if we process it sequentially.

Junior: Would it work to run them in parallel with goroutines?

Senior: Yes, launch each API call as a goroutine and collect the results through a channel. If you use the errgroup package, error handling is clean too.

Interviewer: Why do you use channels instead of mutexes in Go?

Candidate: Channels are based on the idea of transferring ownership of data, so they structurally prevent race conditions. A mutex protects shared data, whereas a channel copies or moves data so that only one goroutine accesses it at a time.

Interviewer: Please explain the usage scenarios for buffered and unbuffered channels.

Candidate: Use an unbuffered channel when you need synchronization. The sender waits for the receiver, so it is well suited to signaling. A buffered channel is useful in the producer-consumer pattern for absorbing differences in speed.

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

Reviewer: The place where this channel is closed is a bit questionable. It could cause a panic.

Author: What's the problem?

Reviewer: You're closing the channel inside the goroutine, but it should be closed on the sender side. If the receiver closes it, the sender will try to write to a closed channel and cause a panic.

⚠️ Cautions

🔗 Related Terms

📚 Learn More