Artemijs
Artemijs Pavlovs

Follow

Artemijs Pavlovs

Follow

Concurrent Go - raw notes

Artemijs's photo
Artemijs
·Nov 23, 2022·

1 min read

Best Video Material:

[YouTube] Jake Wright - Concurrency in Go

[YouTube] Matt KØDVB - Go Class: 23 CSP, Goroutines, and Channels

Best Text Material:

[GitHub] luk4z7 - Go Concurrency Guide [BetterProgramming] Kevin Vogel - Deep Dive into Concurrency of Go

Quick Notes

goroutines - run concurrent code. A lightweight abstraction of virtual threads on top of OS thread

// run a function inside a separate goroutine
go myAwesomeFunction()

channels - solve the problem of communicating safely between concurrently running code

// initialize a channel
ch := make(chan T)
  • close channels only from the sender functions.
  • select is a builtin switch statement for channels. Allows to listen for multiple channels at once and prevents them from blocking one another.
func processSomething(thing string, duration time.Duration, ch chan string) {
    for {
        time.Sleep(time.Second * duration)
        ch <- thing
    }
}

func main() {
    channelOne := make(chan string)
    channelTwo := make(chan string)
    go processSomething("order", 1, channelOne)
    go processSomething("refund", 2, channelTwo)

    for {
        select {
        case thing := <-channelOne:
            log.Println("channelOne:", thing)
        case thing := <-channelTwo:
            log.Println("channelTwo:", thing)
        }
    }
}
 
Share this