Below you will find pages that utilize the taxonomy term “Concurrency”
Wrapping Goroutines to Handle Return Values in Go
Introduction
Concurrency is one of Go’s superpowers, enabling developers to run tasks in parallel using goroutines. A goroutine is launched with the go keyword followed by a function call, as shown below:
package main
import (
"fmt"
"time"
)
func say(s string) {
for i := 0; i < 5; i++ {
time.Sleep(100 * time.Millisecond)
fmt.Println(s)
}
}
func main() {
go say("world")
say("hello")
}
Go playground link to the example
This simple example prints “hello” and “world” concurrently. However, the Go language specification notes that if a function called in a goroutine returns values, those values are discarded. This raises a question: how can we capture and use return values from a goroutine?
Embracing 'Share By Communicating' in Go
Introduction
Concurrency is a core strength of Go, and one of its standout principles is “Share By Communicating.” Unlike traditional approaches that rely on shared memory and locks, Go encourages developers to share data between goroutines by passing it through channels. This method simplifies concurrent programming and helps avoid common issues like race conditions, making your code safer and easier to maintain.
Why does this matter? In many languages, concurrent programs share memory directly, requiring locks to prevent conflicts. This can lead to complex, error-prone code, think deadlocks or subtle bugs that only appear under specific conditions. Go flips this on its head: instead of locking memory, you communicate data through channels, ensuring only one goroutine accesses it at a time by design.