- read

Goroutines: Think You Know Go Basics? Think Again

Phuong Le (@func25) 45

Goroutines: Think You Know Go Basics? Think Again

Goroutines are the heart of Golang, with the efforts of the Go Team, developers can handle tasks concurrently using just the ‘go’ keyword

Phuong Le (@func25)
Level Up Coding
Published in
6 min read15 hours ago

--

Photo by Markus Winkler on Unsplash

Goroutines truly define Golang and thanks to the diligent Go Team, we, the developers, can concurrently manage tasks concurrently with just a sprinkle of the ‘go’ keyword

func main() {
go TaskA()
}

Simple, right? Think about other languages for a moment.

Java, we’re often navigating through Thread and ExecutorService frameworks, and in Python? Threading can get tied up with the Global Interpreter Lock (GIL).

But with Go, things just click and it just works.

1. Goroutines The First Look

Before diving into the inner workings of goroutines, let’s get familiar with its basic usage:

func main() {
go doSomething()

fmt.Println("done")
}

func doSomething() {
fmt.Println("doSomething called")
}

// done

In the example above, doSomething() will be executed concurrently with main(), and thanks to the built-in go keyword, there’s no fuss with external libraries or any of that sort.

“But wait, why am I not seeing the log ‘doSomething called’?”

Ah, there’s a catch.

main() doesn’t wait for the goroutines it launches to complete. So, when you run the program, main() briskly starts doSomething() as a goroutine and without missing a beat, prints ‘done’.

The program might wrap up and say its goodbyes even before doSomething() gets call.

goroutine fork-join model (source: blog.devtrovert.com)

You can give the doSomething goroutine a moment to finish its task in the main function by adding a simple time.Sleep(..):

func main() {
go doSomething()

time.Sleep(time.Second)
fmt.Println("done")
}

func doSomething() {
fmt.Println("doSomething called")
}

// doSomething called
// done