Fragment Description:



In case a channel has a buffer all 'read operations' succeed without blocking if the buffer is not empty, and 'write operations' if the buffer is not full.
These channels are called asynchronous.
Here is an example to demonstrate the difference between them:
Comment/Uncomment the lines below Case-1 and Case-2 and observe the results.


channelBuffered

Go Playground

Last update, on 2015, Fri 9 Oct, 16:15:27

/* ... <== see fragment description ... */

package main

import (
    "fmt"
    "time"
)

func main() {
    // Case-1: no buffer
    // chanMessage := make(chan string)
    // Case-2: with buffer ... the output changes
    chanMessage := make(chan string, 2)
    count := 3
    go func() {
        for i := 1; i <= count; i++ {
            fmt.Println("send message")
            // send to chanMessage
            chanMessage <- fmt.Sprintf("message %d", i)
        }
    }()
    // Pause the main to let the goroutine sends its messages
    time.Sleep(time.Second * 2)
    for i := 1; i <= count; i++ {
        // receive from chanMessage and print
        fmt.Println(<-chanMessage)
    }
}

/* Expected Output:
Case-1: without a buffer
send message
message 1
send message
send message
message 2
message 3
Case-2: with a buffer
send message
send message
send message
message 1
message 2
message 3
*/
/*
Here we see that all writing operations are performed without waiting for
 the first read for the buffer of the channel allows to store all three messages.
By changing channels capacity we can control the amount of information
 being processed thus limiting throughput of a system.
*/



Comments