Skip to content

Channel based concurrency in Go

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")
}

Disclaimer
  1. License under CC BY-NC 4.0
  2. Copyright issue feedback me#imzye.me, replace # with @
  3. Not all the commands and scripts are tested in production environment, use at your own risk
  4. No privacy information is collected here
Try iOS App