Golang Funny: Play with Channel

Golang have a funny toy: Channel. Here has some words from the specification:

A channel provides a mechanism for two concurrently executing functions to synchronize execution and communicate by passing a value of a specified element type.

Yep! It is boring and dull. You can’t understand it when you read it first time. Actually, you can think of it as a PIPE or a FIFO queue. It’s lightweight and simple. Channel is not of Golang origin. It also appears in some other languages(embedded). And most of time, it’s a function as a part of a huge, complexly and heavy message queue system.

OK! Let’s have some fun.

Common way: Producer / Consumer

This is the most common way to use a channel. A producer makes things and put them into the channel. And a consumer get them from the channel. On by on, in order. If the channel is full, the producer must wait. Otherwise, if the channel is empty, the consumer must wait.

You can get full source from here. Running it at local is better.

Producer:

<br />
func producer(c chan int64, max int) {<br />
    defer close(c)<br />
    for i:= 0; i &lt; max; i ++ {<br />
        c &lt;- time.Now().Unix()<br />
    }<br />
}<br />

The producer makes a number of ‘max’ int64, and put them into the channel ‘c’. Notice that, here is a defer for closing the channel.

Consumer:

<br />
func consumer(c chan int64) {<br />
    var v int64<br />
    ok := true<br />
    for ok {<br />
        if v, ok = &lt;-c; ok {<br />
            fmt.Println(v)<br />
        }<br />
    }<br />
}<br />

Read int64s from the channel one by one, and print them on to the screen. When the channel closed, the variable ‘ok’ will be set to ‘false’.

Auto-increment ID generator

If we let the producer makes a sequence of integer. It will be a auto-increment ID generator. I wrote a package that encapsulates it. You can found it at here. The usage can be found at here.

<br />
type AutoInc struct {<br />
    start, step int<br />
    queue chan int<br />
    running bool<br />
}</p>
<p>func New(start, step int) (ai *AutoInc) {<br />
    ai = &amp;AutoInc{<br />
        start: start,<br />
        step: step,<br />
        running: true,<br />
        queue: make(chan int, 4),<br />
    }<br />
    go ai.process()<br />
    return<br />
}</p>
<p>func (ai *AutoInc) process() {<br />
    defer func() {recover()}()<br />
    for i := ai.start; ai.running ; i=i+ai.step {<br />
        ai.queue &lt;- i<br />
    }<br />
}</p>
<p>func (ai *AutoInc) Id() int {<br />
    return &lt;-ai.queue<br />
}</p>
<p>func (ai *AutoInc) Close() {<br />
    ai.running = false<br />
    close(ai.queue)<br />
}<br />

Semaphore

Semaphore is a funny usage of Channel. Here is a demo from “Effective Go“. You should have read it, haven’t you? If not, read it now…

I have used the channel as a semaphore in the gearman-go, a package for Gearman job server. You can found the codes here. Line 232, the Worker.exec will be blocked by Worker.limit.

<br />
var sem = make(chan int, MaxOutstanding)</p>
<p>func handle(r *Request) {<br />
    sem &lt;- 1    // Wait for active queue to drain.<br />
    process(r)  // May take a long time.<br />
    &lt;-sem       // Done; enable next request to run.<br />
}</p>
<p>func Serve(queue chan *Request) {<br />
    for {<br />
        req := &lt;-queue<br />
        go handle(req)  // Don't wait for handle to finish.<br />
    }<br />
}<br />

Randomized sequence

Of course, we could modify the auto-increment ID generator. Let the producer makes randomized number and put into the channel. But, it’s not funny enough. Right?

Here is another randomized sequence. It was inspired by the specification. It produces 0 or 1 randomly:

<br />
func producer(c chan int64, max int) {<br />
    defer close(c)<br />
    for i:= 0; i &lt; max; i ++ {<br />
        select { // randomized select<br />
            case c &lt;- 0:<br />
            case c &lt;- 1:<br />
        }<br />
    }<br />
}<br />

The timeout timer

If a channel was blocked at read/write, it will be blocked forever. Until the channel was closed, then a panic raised. The channel has no timeout timer build in. And it looks like there is no plan to add a timer into channel. But most of time, we need a timeout mechanism. Eg. a producer executed, and something wrong with it, then nothing put into the channel. The consumer was blocked now, until the channel was closed. Close the channel for every time? No! That’s not a good idea.

Here is a solution.

<br />
    c := make(chan int64, 5)<br />
    defer close(c)<br />
    timeout := make(chan bool)<br />
    defer close(timeout)<br />
    go func() {<br />
        time.Sleep(time.Second) // wait a second<br />
        timeout &lt;- true // put a bool value into the channel<br />
    }()<br />
    select {<br />
        case &lt;-timeout: // timeout<br />
            fmt.Println(&quot;timeout...&quot;)<br />
        case &lt;-c: // received a data<br />
            fmt.Println(&quot;Read a data.&quot;)<br />
    }<br />

Have you noticed the select statement? Which channel receive data, which sub-branch execution. So … do we need more explanation?

This also used in the client of gearman-go, line 238.

Further: Thx @mjq. The time.After is really better solution. And I read the source codes at src/pkg/time/sleep.go, line 74. Internal implementation is same as the above.

One more thing

This is not only a introduction about golang channel, but also a English writing exercise. So, if you have some other ideas about golang channel usage, share them with me! If you found some issues in my blog, plz point out them for me. thx!

[2012.06.26] updated!
Using close to broadcast

9 thoughts on “Golang Funny: Play with Channel”

  1. Nice post. There’s an even easier timeout pattern available now, using time.After. Instead of starting a separate goroutine you can do just:

    select {
    case <-time.After(time.Second):
    fmt.Println("timeout...")
    case <-c:
    fmt.Println("Read a date.")
    }

  2. 1. Common way: Producer / Consumer

    func producer(max int) (c <-chan int) {
    c = make( chan int )
    go func() {
    for i:= 0; i < max; i ++ {
    c <- time.Now().Unix()
    }
    close(c)
    }()

    return

    }

    func consumer(c data ?

  3. 我去居然内容被吞了

    func producer(max int) (c <-chan int) {
    c = make( chan int )
    go func() {
    for i:= 0; i < max; i ++ {
    c <- time.Now().Unix()
    }
    close(c)
    }()

    return

    }

    func consumer(c <- chan int64) {
    var v int64
    ok := true
    for v, ok := range c {
    fmt.Println(v)
    }

    }

    func main() {
    i := 10
    consumer(producer(10))
    }

Leave a Reply

Your email address will not be published. Required fields are marked *