Simple function throttler in golang

Go is fun, I love writing code in go. I am rewriting the whole backend for http://www.websrvr.in/ using go and am loving every moment of it. Here is a small throttler I wrote to throttle goroutines in my code. The simplicity of this blows my mind, In another language I would have to bend over backwards to get this done.

Play with it in Go playground

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package main

import (
    "fmt"
    "sync"
    "time"
)

//start of throttler
type Throttler chan bool

func NewThrottler(n int) Throttler {
    return make(chan bool, n)
}

func (t Throttler) Fill() Throttler {
    t <- true
    fmt.Print("+") //for demo
    return t
}

func (t Throttler) Drain() {
    <-t
    fmt.Print("-") //for demo
}

//end of throttler
//this is all the code you need.
//Also remove the fmt.Print statements if you want to use this in your code

func main() {
    //creates a throttler which runs a maximum of 2 routines concurrently
    t := NewThrottler(2)

    //demo code
    st := time.Now()
    wg := &sync.WaitGroup{}
    for i := 0; i < 10; i++ {
        wg.Add(1)
        go func() {
            //used to throttle
            defer wg.Done()
            defer t.Fill().Drain()
            fmt.Print("W")
            time.Sleep(1 * time.Millisecond) //to simulate work
        }()
    }

    wg.Wait()
    fmt.Println("\nTime to finish:", time.Now().Sub(st))
}

//Output
//+W+W--+W+W--+W+W--+W+W--+W+W--
//Time to finish: 5.756916ms