// lesson: goroutines-basics

Goroutines Basics

A goroutine is a lightweight thread managed by the Go runtime. Starting one costs a few kilobytes of stack, so programs routinely run thousands of them.

go func() {
	fmt.Println("hello from a goroutine")
}()

The go keyword starts the function in a new goroutine and returns immediately. The program exits when main returns โ€” it does not wait for other goroutines, which is why synchronization matters.

Waiting for goroutines: sync.WaitGroup

Since the program won't wait for goroutines on its own, you need something that will. sync.WaitGroup is a counter built for exactly that: call Add(n) before starting n goroutines, have each one call Done() when it finishes (usually via defer), and call Wait() to block until every Done() has landed.

var wg sync.WaitGroup
results := make([]int, 2)

wg.Add(2)
go func() {
	defer wg.Done()
	results[0] = workA()
}()
go func() {
	defer wg.Done()
	results[1] = workB()
}()

wg.Wait()
fmt.Println(results[0] + results[1])

Each goroutine writes to its own slot in results, so there's no data race even though both run at the same time โ€” two goroutines writing to the same variable without synchronization is a race, and go test -race would catch it. Read results only after Wait() returns, once every goroutine is guaranteed to have finished writing.

โ€บ Run Work Concurrently

10 pts

Implement Sum(nums []int) int so that it splits the slice in half and sums each half in its own goroutine, combining the results.

Log in to submit a solution and earn points.