notes blog about

Concurrent programming

Why?

Go enables two styles of concurrent programming:

  1. Communicating sequential processes (CSP) - see below
  2. Shared memory multithreading - more traditional model

Goroutines

f()     // call f(); wait for it to return
go f()  // create a new goroutine that calls f(); don't wait

Channels - a way for gouroutines to

Select

Example

package main

import (
    "fmt"
    "time"
)

func main() {
    ch1 := make(chan string)
    ch2 := make(chan string)

    go func() {
        for {
            ch1<- "from 1"
            time.Sleep(time.Second * 2)
        }
    }()

    go func() {
        for {
            ch2<- "from 2"
            time.Sleep(time.Second * 3)
        }
    }()

    go func() {
        for {
            select {
            case msg1 := <-ch1:
                fmt.Println(msg1)
            case msg2 := <-ch2:
                fmt.Println(msg2)
            default:
                fmt.Println("nothing ready")
                time.Sleep(time.Second * 1)
            }
        }
    }()

    var input string
    fmt.Scanln(&input)
}

More