0
0
Goprogramming~5 mins

Channel synchronization in Go

Choose your learning style9 modes available
Introduction

Channel synchronization helps different parts of a Go program talk to each other safely and wait for each other when needed.

When you want one part of your program to wait for another part to finish a task.
When you want to send data safely between different running parts (goroutines).
When you want to make sure tasks happen in order without mixing up results.
Syntax
Go
ch := make(chan Type)

// Send value to channel
ch <- value

// Receive value from channel
value := <-ch

Channels are typed, so you must specify the type of data they carry.

Sending and receiving on channels can block (wait) until the other side is ready, which helps with synchronization.

Examples
This example creates a channel for integers, sends 5 into it, and receives it back.
Go
ch := make(chan int)

// Sending
ch <- 5

// Receiving
num := <-ch
This example uses a channel to wait for a goroutine to finish its work before continuing.
Go
done := make(chan bool)
go func() {
    // Do some work
    done <- true // Signal completion
}()

<-done // Wait for signal
Sample Program

This program starts a worker goroutine that prints a message and then signals completion through a channel. The main function waits for this signal before printing its final message.

Go
package main

import (
	"fmt"
)

func worker(done chan bool) {
	fmt.Println("Working...")
	done <- true // Signal that work is done
}

func main() {
	done := make(chan bool)
	go worker(done)
	<-done // Wait for worker to finish
	fmt.Println("Worker finished")
}
OutputSuccess
Important Notes

Channels block the sender until the receiver is ready, and vice versa, which helps coordinate tasks.

Buffered channels can hold some values without blocking, but unbuffered channels always synchronize sender and receiver.

Always close channels only when you want to signal no more values will be sent; closing a channel is not needed for synchronization.

Summary

Channels let goroutines communicate and wait for each other safely.

Sending and receiving on channels can pause execution until the other side is ready, which helps with synchronization.

Use channels to coordinate tasks and share data between goroutines without conflicts.