Golang channels

Definition

Channels are the pipes that connect concurrent goroutines. You can send values into channels from one goroutine and receive those values into another goroutine.

Usage Scenario

To download multiple files from a server, you can use go routines to asynchronously run an algorithm to download a file, while the channel tells that algorithm what file to download.

About

Creation

Sizing a Channel

unlimitedbut blocking on writing if nothing is listening on other end

books := make(chan string)


limited, blocks writing when channel is full

books := make(chan string, size int)

Writing


<- on the right side of the channel is to send the content on the right into the channel


*note: since messages sized to unlimited, it will block unless something is reading from the channel, therefore, use of Go-routine is used to asynchronously run that block


books := make(chan string)
go func() { books <- "black lagoon" }()

Reading

<- on the left side of the channel is to read from the channel, block if it is empty

msg <- messages


Complete Code Block


package main

import "fmt"

func main() {
    books := make(chan string)

    go func() {  books <- "black lagoon" }()

    book := <- books

    fmt.Println(book)
}

Comments

Popular posts from this blog

ColdFusion in an Enterprise Environment - Part 1 - Understanding how to use SubVersion (SVN)

coldfusion builder 2 extension not displaying browse button on type=projectdir

Being Thread Safe in Coldbox/Coldfusion