Channel based concurrency in Go
Introduction
Go is a programming language that is designed to make concurrency easy and efficient. One of its most powerful features is the use of channels for communication between concurrent processes. In this blog post, we will explore how to implement channel-based concurrency in Go.
Demo code
package main
import (
"fmt"
"time"
)
func worker(ch chan int) {
time.Sleep(time.Second)
fmt.Println(time.Now())
<-ch
}
func main() {
// task number
count := 10
ch := make(chan int, 3)
defer close(ch)
for i := 0; i < count; i++ {
ch <- 0
go worker(ch)
}
// wait task finish
for {
if len(ch) == 0 {
break
}
time.Sleep(time.Second)
}
fmt.Printf("# DONE\n")
}
Leave a message
Disclaimer
- Welcome to visit the knowledge base of SRE and DevOps!
- License under CC BY-NC 4.0
- Made with Material for MkDocs and improve writing by generative AI tools
- Copyright issue feedback me#imzye.com, replace # with @