UNB/ CS/ David Bremner/ teaching/ cs2613/ labs/ Lab 21

Before the lab

Getting started

Goroutines

// A _goroutine_ is a lightweight thread of execution.

package main

import (
	"fmt"
	"time"
)

func f(from string) {
	for i := range 3 {
		fmt.Println(from, ":", i)
	}
}

func main() {

	// Suppose we have a function call `f(s)`. Here's how
	// we'd call that in the usual way, running it
	// synchronously.
	f("direct")

	// To invoke this function in a goroutine, use
	// `go f(s)`. This new goroutine will execute
	// concurrently with the calling one.
	go f("goroutine")

	// You can also start a goroutine for an anonymous
	// function call.
	go func(msg string) {
		fmt.Println(msg)
	}("going")

	// Our two function calls are running asynchronously in
	// separate goroutines now. Wait for them to finish
	// (for a more robust approach, use a [WaitGroup](waitgroups)).
	time.Sleep(time.Second)
	fmt.Println("done")
}
$ go run goroutines.go 
direct : 0
direct : 1
direct : 2
goroutine : 0
goroutine : 1
going
goroutine : 2
done

Channels

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

package main

import "fmt"

func main() {

	// Create a new channel with `make(chan val-type)`.
	// Channels are typed by the values they convey.
	messages := make(chan string)

	// _Send_ a value into a channel using the `channel <-`
	// syntax. Here we send `"ping"`  to the `messages`
	// channel we made above, from a new goroutine.
	go func() { messages <- "ping" }()

	// The `<-channel` syntax _receives_ a value from the
	// channel. Here we'll receive the `"ping"` message
	// we sent above and print it out.
	msg := <-messages
	fmt.Println(msg)
}
$ go run channels.go
1
3
2
7
6
8
4
0
9
5

Range over Channels

package main

import "fmt"

func main() {

    // We'll iterate over 2 values in the `queue` channel.
    queue1 := make(chan string, 2)
    queue1 <- "one"
    queue1 <- "two"
    close(queue1)
    queue2 := make(chan string, 2)

    // This `range` iterates over each element as it's
    // received from `queue`. Because we `close`d the
    // channel above, the iteration terminates after
    // receiving the 2 elements.
    go func() {



    }()

    for elem := range queue2 {
        fmt.Println(elem)
    }
}
go run queues.go
one
two

Workgroups

// To wait for multiple goroutines to finish, we can
// use a *wait group*.

package main

import (
    "fmt"
    "time"
    "sync"
)

// This is the function we'll run in every goroutine.
func worker(id int) {
    fmt.Printf("Worker %d starting\n", id)
    time.Sleep(time.Second)
    // Sleep to simulate an expensive task.
    fmt.Printf("Worker %d done\n", id)
}

func main() {

    // This WaitGroup is used to wait for all the
    // goroutines launched here to finish. Note: if a WaitGroup is
    // explicitly passed into functions, it should be done *by pointer*.
    var wg sync.WaitGroup
    var chans [5](chan int);
    for i:=range 5 {
        chans[i] = make(chan int)
    }

    wg.Go(func() {
         // write to channel
    })
    // Launch several goroutines using `WaitGroup.Go`
    for i := 1; i <= 5; i++ {
        wg.Go(func() {
            fmt.Printf("waiting for %d\n",i-1);
            // read from channel
            worker(i)
            if (i<5) {
                // write to channel
            }
        })
    }

    // Block until all the goroutines started by `wg` are
    // done. A goroutine is done when the function it invokes
    // returns.
    wg.Wait()

    // Note that this approach has no straightforward way
    // to propagate errors from workers. For more
    // advanced use cases, consider using the
    // [errgroup package](https://pkg.go.dev/golang.org/x/sync/errgroup).
}

- Output should be something like the following. Notice the order the
  start waiting is arbitrary, but the order the workers actually start
  is fixed.

[[!format sh