Getting a grip on Go's Goroutines and Channels (Part 2)

This is a continuation of my article

https://ikeoha.com/post/getting-a-grip-on-gos-goroutines-and-channels-part-1/

An important information to note about go: The main func is actually a goroutine on it’s own, keep this in mind it’ll come in handy later on

Let me give a simple but a bit more intermidiate example of goroutines and channels in action:


func main() {
    students := []string{“Chidi”, “Chike”, “Afam”}

    // here we’re creating a channel which can send and receive
    aChannel := make(chan string}

    // goroutines basically make functions run concurrently, here we’re
    // creating an anonymous function
    go func() {
        for _, name := range students {
            aChannel <- name
}
    }()

    go func() {
        // yes we’re ranging over the channel here
        for studentName:= range aChannel {
            // receive name from aChannel channel and print it out
            log.Println(studentName)
        }
}()

// i’ll explain this further after the code
<-time.After(time.Second * 5)
}

Hopefully the comments in the code above explain enough about the code for you to understand. Notice at the bottom of the code above there’s the line <-time.After(time.Second * 5), well remember when i said the main function is a goroutine too, now what does that have to do with anything. Well see the main function runs immediately runs once the code is executed and doesn’t wait for the goroutines that run into it before exiting, so the code <-time.After(time.Second * 5) blocks the main goroutine or main function from running and executing giving other goroutines time to run.

How does this time.After(time.Second * 5) actually do this. Well see there is a small piece of information that I kept away and that is channels block until they receive some value. So that code <-time.After(time.Second * 5) has basically blocked the main goroutine from exiting for 5 seconds giving the main function enough time to let other goroutines run. This is a typically bad way to do this though and should be avoided as much as possible.

That wraps up part 2 i’ll make part 3 as i get a more solid understanding of goroutines and channels.