Skip to content

Channel based concurrency in Go

homepage-banner

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