Level: BeginnerGo Programs

Go Goroutine Programs with Output: WaitGroup, Once and Results

Updated 16 min read
Go Goroutine Programs featured image: WaitGroup and goroutine results output

Go goroutine programs run several pieces of work at the same time, which is the feature Go is most famous for. A goroutine is a very light thread managed by Go, so you can start thousands of them without slowing your machine. In this post, you will write twelve goroutine programs with their exact output, with the logic explained in code comments, including the interview favourite: print odd and even numbers alternately with two goroutines.

This post builds on our Go function programs, because every goroutine runs a function. For the theory, read the Go goroutines guide for beginners and WaitGroup and Mutex explained. All programs were tested on Go 1.27.

What are Go Goroutine Programs?

Go goroutine programs start a function with the go keyword, so it runs alongside the rest of the program. The Go runtime decides which goroutine runs on which CPU core, and switches between them very quickly.

Think of a restaurant kitchen. One cook making every dish one by one is slow. With goroutines, you hire many cooks who work at the same time, and the head chef (the Go runtime) tells each one what to do. A WaitGroup is the head chef waiting until every dish is ready before serving.

Why Go Goroutine Programs Matter

Modern servers handle thousands of requests at once. For example, a web server starts one goroutine per request, a crawler fetches many pages in parallel and a report job processes files on all CPU cores. So Go goroutine programs are at the heart of Go backend work.

  • Speed: split big work across CPU cores.
  • Waiting: do other work while one task waits for the network or disk.
  • Interviews: odd-even printing, WaitGroup bugs and deadlocks are very common questions.

How Go Goroutine Programs Work

go f() starts f in a new goroutine and returns at once. The main function does not wait for it. So we use a sync.WaitGroup: we tell it how many goroutines to wait for, each goroutine says “done” at the end, and Wait blocks until the count reaches zero.

Go goroutine programs diagram showing main starting goroutines and waiting with a WaitGroup
main starts several goroutines with wg.Go, each is marked done when it finishes, and wg.Wait blocks until all of them are done.

The table below lists the goroutine tools in this post.

ToolWhat it doesNotes
go f()Starts f in a new goroutineReturns immediately
sync.WaitGroupWaits for many goroutinesAdd, Done, Wait
wg.Go(f)Add, go and Done in one callSince Go 1.25
sync.OnceRuns code only onceSafe across goroutines
runtime.NumGoroutineCounts live goroutinesUseful for leak checks
go run -raceFinds data racesUse in testing

Basic Go Goroutine Programs

These first Go goroutine programs start goroutines and wait for them. If goroutines are new to you, begin with Program 1. It starts just one goroutine.

Program 1: Your First Goroutine

package main

import (
    "fmt"  // fmt prints text on the screen
    "sync" // sync has tools for waiting on goroutines
)

// greet prints a hello message. It will run inside a goroutine.
func greet(name string, wg *sync.WaitGroup) {
    defer wg.Done() // defer runs this when greet ends; Done says "I am finished"
    fmt.Println("Hello,", name)
}

func main() {
    // wg (wait group) counts the goroutines we must wait for.
    var wg sync.WaitGroup

    wg.Add(1)             // we are about to start one goroutine
    go greet("Asha", &wg) // go runs greet in a new goroutine; &wg passes a pointer to wg
    wg.Wait()             // wait here until greet calls Done

    fmt.Println("main is done")
}
Hello, Asha
main is done

First, wg.Add(1) tells the WaitGroup that one goroutine is coming. Then the go keyword starts greet in the background, and main moves on to wg.Wait(). When greet calls Done, the wait ends and main prints its last line.

Program 2: Start Goroutines and Wait with WaitGroup

package main

import (
    "fmt"
    "sync"
)

func main() {
    var wg sync.WaitGroup
    // make creates a slice with 3 empty strings. Each goroutine writes only its own slot.
    results := make([]string, 3)

    for i := range 3 { // i takes the values 0, 1 and 2
        wg.Add(1) // tell the WaitGroup one more goroutine is coming
        go func() {
            defer wg.Done() // say "finished" when this goroutine ends
            // Sprintf builds a string instead of printing it.
            results[i] = fmt.Sprintf("task %d done", i+1)
        }()
    }

    wg.Wait() // block here until all three called Done
    for _, result := range results {
        fmt.Println(result)
    }
}
task 1 done
task 2 done
task 3 done

The loop starts three small goroutines, and each one fills its own slot. Goroutines may finish in any order. We keep the output stable by writing into fixed slots and printing after Wait. Since Go 1.22, each loop pass has its own i, so every goroutine sees the right number.

Program 3: The Shorter wg.Go Form

Go 1.25 added wg.Go, which does Add, go and Done for you.

package main

import (
    "fmt"
    "sync"
)

func main() {
    var wg sync.WaitGroup
    squares := make([]int, 5)

    for i := range 5 {
        // wg.Go starts the function in a new goroutine and calls Done for you (Go 1.25+).
        wg.Go(func() {
            squares[i] = (i + 1) * (i + 1)
        })
    }
    wg.Wait()
    fmt.Println(squares)
}
[1 4 9 16 25]

Each goroutine squares one number and stores it in its own slot. wg.Go counts the goroutine and marks it done for you. This form removes the most common WaitGroup bug, which is forgetting Add or Done.

Program 4: What Happens Without Waiting

package main

import "fmt"

func main() {
    go fmt.Println("from goroutine") // may never get a chance to run
    fmt.Println("main is finishing")
    // No wait here. When main returns, the whole program stops.
}

Most runs print only this line.

main is finishing

When main returns, every goroutine is stopped at once. The goroutine usually has no time to print, which is why you always need a WaitGroup or a channel. On a busy machine it might print, so never rely on either result.

Parallel Work in Go Goroutine Programs

These Go goroutine programs split one big job into parts.

Program 5: Sum a Slice in Parallel

package main

import (
    "fmt"
    "sync"
)

func main() {
    // Step 1: fill a slice with the numbers 1 to 1000.
    numbers := make([]int, 1000)
    for i := range numbers {
        numbers[i] = i + 1
    }

    // Step 2: split the work into 4 parts, one goroutine each.
    parts := 4
    partial := make([]int, parts) // one result slot per goroutine
    size := len(numbers) / parts  // 250 numbers per part
    var wg sync.WaitGroup

    for part := range parts {
        wg.Go(func() {
            // Each goroutine sums its own chunk of the slice.
            start := part * size
            end := start + size
            for _, number := range numbers[start:end] { // [start:end] takes a piece of the slice
                partial[part] += number
            }
        })
    }
    wg.Wait()

    // Step 3: combine the partial sums in main.
    total := 0
    for _, sum := range partial {
        total += sum
    }
    fmt.Println(partial, total)
}
[31375 93875 156375 218875] 500500

Each goroutine adds up 250 numbers and writes only its own partial[part]. So there is no shared counter and no data race. Finally, main adds the four parts, and the total matches the formula 1000 x 1001 / 2.

Program 6: Get One Result Back with a Channel

package main

import "fmt"

// addNumbers adds two numbers and sends the answer into the channel.
func addNumbers(first, second int, result chan int) {
    result <- first + second // <- sends a value into the channel
}

func main() {
    // A channel is a pipe that goroutines use to pass values.
    result := make(chan int)

    go addNumbers(20, 22, result) // runs in a new goroutine

    // <-result waits until a value arrives, then reads it.
    sum := <-result
    fmt.Println("Sum:", sum)
}
Sum: 42

This is the easiest way to get an answer back from a goroutine. The goroutine sends the sum into the channel. Meanwhile, main waits at <-result until the value arrives, so no WaitGroup is needed here.

Program 7: Collect Results with a Channel

package main

import (
    "fmt"
    "slices"
    "sync"
)

func main() {
    words := []string{"go", "rust", "python", "c"}
    lengths := make(chan int, len(words)) // buffered: it can hold all results
    var wg sync.WaitGroup

    for _, word := range words {
        wg.Go(func() {
            lengths <- len(word) // send each result into the channel
        })
    }
    wg.Wait()      // wait until every goroutine has sent
    close(lengths) // no more values, so range can stop

    var all []int
    for length := range lengths { // read every value from the channel
        all = append(all, length) // append adds a value to the end of the slice
    }
    slices.Sort(all) // arrival order is random, so sort
    fmt.Println(all)
}
[1 2 4 6]

The buffered channel lets every goroutine send without waiting. We close it after Wait, so the range loop knows when to stop. Then sorting makes the output the same every time. Channels get their own post next.

Program 8: sync.Once for One-Time Setup

package main

import (
    "fmt"
    "sync"
)

func main() {
    var once sync.Once
    var wg sync.WaitGroup
    setupCount := 0

    for range 10 { // start 10 goroutines
        wg.Go(func() {
            // Only the first caller runs the function; others wait for it.
            once.Do(func() {
                setupCount++
            })
        })
    }
    wg.Wait()
    fmt.Println("setup ran", setupCount, "time")
}
setup ran 1 time

Ten goroutines all call once.Do, but only the first call runs the setup. The other nine skip it. sync.Once is perfect for loading a config or opening a database connection the first time it is needed, even when many goroutines ask at once.

Most Asked Interview Go Goroutine Programs

These Go goroutine programs come up in interviews again and again.

Program 9: Print Odd and Even Numbers Alternately

Two goroutines take turns. Each one waits for its turn on a channel, prints, and hands the turn to the other.

package main

import (
    "fmt"
    "sync"
)

func main() {
    const limit = 10
    oddTurn := make(chan bool)  // a signal: "odd, it is your turn"
    evenTurn := make(chan bool) // a signal: "even, it is your turn"
    var wg sync.WaitGroup

    // Odd printer: prints 1, 3, 5, ...
    wg.Go(func() {
        for i := 1; i <= limit; i += 2 {
            <-oddTurn // wait for my turn
            fmt.Println("odd :", i)
            evenTurn <- true // give the turn to the even printer
        }
    })

    // Even printer: prints 2, 4, 6, ...
    wg.Go(func() {
        for i := 2; i <= limit; i += 2 {
            <-evenTurn // wait for my turn
            fmt.Println("even:", i)
            if i < limit {
                oddTurn <- true // hand back unless we are finished
            }
        }
    })

    oddTurn <- true // start the game: odd goes first
    wg.Wait()
}
odd : 1
even: 2
odd : 3
even: 4
odd : 5
even: 6
odd : 7
even: 8
odd : 9
even: 10

Unbuffered channels act like a baton in a relay race. Only one goroutine holds the turn at a time, so the order is always correct. The if i < limit check stops the even printer from handing a turn that nobody will take.

Program 10: Download Simulator with Many Workers

package main

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

// download pretends to download a file by waiting for a short time.
func download(file string, delayMs int) string {
    time.Sleep(time.Duration(delayMs) * time.Millisecond) // pause like a slow network
    return file + " ok"
}

func main() {
    files := []string{"a.pdf", "b.jpg", "c.zip"}
    delays := []int{300, 100, 200}
    results := make([]string, len(files))
    start := time.Now()

    var wg sync.WaitGroup
    for i, file := range files {
        wg.Go(func() {
            results[i] = download(file, delays[i])
        })
    }
    wg.Wait()

    fmt.Println(results)
    // All three run at the same time, so the total is about the slowest one.
    fmt.Println("under 400ms:", time.Since(start) < 400*time.Millisecond)
}
[a.pdf ok b.jpg ok c.zip ok]
under 400ms: true

Each file gets its own goroutine and its own result slot. Run one after another, the downloads would take 600 ms. In parallel, they take about 300 ms, which is the time of the slowest file.

Program 11: Count Goroutines Before and After

package main

import (
    "fmt"
    "runtime"
    "sync"
)

func main() {
    fmt.Println("at start:", runtime.NumGoroutine()) // just main

    var wg sync.WaitGroup
    stop := make(chan struct{}) // struct{} carries no data, it is only a signal
    for range 5 {
        wg.Go(func() {
            <-stop // block until we close the channel
        })
    }
    fmt.Println("while running:", runtime.NumGoroutine() >= 6) // main plus 5 more

    close(stop) // wake every goroutine at once
    wg.Wait()
    fmt.Println("finished cleanly")
}
at start: 1
while running: true
finished cleanly

Five goroutines wait on the stop channel, so the count grows to at least six. Closing a channel wakes every goroutine waiting on it. Checking NumGoroutine in tests is a simple way to spot goroutine leaks.

Program 12: A Goroutine Panic Recovered Safely

package main

import (
    "fmt"
    "sync"
)

// safeGo runs a job in a goroutine and catches any panic inside it.
func safeGo(wg *sync.WaitGroup, name string, job func()) {
    wg.Add(1)
    go func() {
        defer wg.Done()
        // This deferred function runs last, even after a panic.
        defer func() {
            // recover only works inside the same goroutine that panicked.
            problem := recover() // nil if there was no panic
            if problem != nil {
                fmt.Println(name, "recovered:", problem)
            }
        }()
        job()
    }()
}

func main() {
    var wg sync.WaitGroup
    safeGo(&wg, "job-1", func() {
        var scores map[string]int // a nil map, never created with make
        scores["x"] = 1           // panics: you cannot write to a nil map
    })
    wg.Wait()
    fmt.Println("main still running")
}
job-1 recovered: assignment to entry in nil map
main still running

The job writes to a nil map, which causes a panic. The deferred function catches it with recover and prints a message instead. A panic in any goroutine crashes the whole program unless that goroutine recovers it, so this wrapper protects every background job.

Sequential vs Concurrent Go Goroutine Programs

Most Go goroutine programs start from one question: one by one, or at the same time? The diagram and table below compare the two.

Go goroutine programs comparison of sequential and concurrent work
Sequential code runs tasks one after another, while goroutines run them at the same time and finish when the slowest task ends.
FeatureSequentialGoroutines
Total time for waitsSum of all tasksAbout the slowest task
Order of resultsFixedRandom unless you control it
Shared dataSafeNeeds channels or a mutex
Code complexitySimpleA little more
Best forShort, dependent stepsMany independent tasks

So use goroutines when tasks are independent and spend time waiting. Keep code sequential when each step depends on the one before.

Common Mistakes in Go Goroutine Programs

  • Not waiting: main exits and kills every goroutine, so use a WaitGroup or channel.
  • wg.Add inside the goroutine: Wait may run before Add. Call Add before go, or use wg.Go.
  • Copying a WaitGroup: pass it as *sync.WaitGroup, or Done changes a copy and Wait never returns.
  • Shared counters without a lock: many goroutines writing one variable cause a data race.
  • Forgetting to stop goroutines: goroutines that block forever leak memory.

Best Practices for Go Goroutine Programs

  • Prefer wg.Go on Go 1.25 and later, since it cannot forget Add or Done.
  • Give each goroutine its own result slot, or send results on a channel.
  • Run tests with -race, as shown in our Go race detector guide.
  • Recover inside long-running goroutines, so one bug does not crash the server.
  • Always have a way to stop goroutines, such as closing a channel or a context.

Go Goroutine Programs Interview Questions and Answers

Interviewers ask these Go goroutine programs more than any other concurrency questions. Each program is complete, with real output from Go 1.27.

Basics Questions

Q1. What is the difference between a goroutine and an OS thread?

A goroutine starts with a tiny stack of a few kilobytes that grows as needed, while an OS thread usually reserves about 1 MB. The Go runtime runs many goroutines on a few threads, so starting 100,000 goroutines is normal.

Q2. What does this program print?

package main

import "fmt"

func main() {
    numbers := make(chan int) // unbuffered channel
    numbers <- 1              // nobody is receiving, so this waits forever
    fmt.Println(<-numbers)
}
fatal error: all goroutines are asleep - deadlock!

An unbuffered send waits for a receiver. main is the only goroutine, and it is stuck sending, so Go detects a deadlock and stops.

Q3. What is wrong with passing a WaitGroup by value?

package main

import (
    "fmt"
    "sync"
)

// work gets a copy of the WaitGroup, not the real one.
func work(wg sync.WaitGroup) {
    defer wg.Done()
    fmt.Println("working")
}

func main() {
    var wg sync.WaitGroup
    wg.Add(1)
    go work(wg)
    wg.Wait()
}
fatal error: all goroutines are asleep - deadlock!

Done lowers the counter of the copy, so the real counter stays at 1 and Wait never returns. Pass &wg and take *sync.WaitGroup. go vet also warns about this copy.

Q4. Does a goroutine run on a new CPU core?

Not always. The Go scheduler decides. With GOMAXPROCS set to the number of cores (the default), goroutines can run in parallel, but they may also share one core and take turns.

Output Questions on Go Goroutine Programs

Q5. What does this program print?

package main

import (
    "fmt"
    "sync"
)

func main() {
    var mu sync.Mutex // mu (mutex) lets only one goroutine in at a time
    var wg sync.WaitGroup
    count := 0
    for range 1000 {
        wg.Go(func() {
            mu.Lock()
            count++ // only one goroutine at a time gets here
            mu.Unlock()
        })
    }
    wg.Wait()
    fmt.Println(count)
}
1000

Without the mutex, the result could be less than 1000, because two goroutines could read the same old value. Mutexes get their own post soon.

Q6. What does this program print?

package main

import (
    "fmt"
    "sync"
)

func main() {
    var wg sync.WaitGroup
    results := make([]int, 3)
    for i := range 3 {
        wg.Go(func() {
            results[i] = i * 10
        })
    }
    wg.Wait()
    fmt.Println(results)
}
[0 10 20]

Each goroutine captures its own i (Go 1.22 and later), so every slot gets the right value. That is why the slice holds 0, 10 and 20.

Q7. How many goroutines does a plain program start with?

One, the goroutine running main. The runtime also has some system goroutines, but runtime.NumGoroutine() reports 1 at the start of a simple program.

Q8. What does this program print?

package main

import (
    "fmt"
    "sync"
)

func main() {
    var wg sync.WaitGroup
    done := make(chan string, 2) // room for two messages

    wg.Go(func() {
        done <- "first"
    })
    wg.Wait() // "first" is surely sent before we go on

    wg.Go(func() {
        done <- "second"
    })
    wg.Wait()

    close(done)
    for message := range done {
        fmt.Println(message)
    }
}
first
second

The first Wait makes sure “first” is sent before the second goroutine starts, so the order is fixed. A WaitGroup can be reused after Wait returns.

Design Questions

Q9. How do you limit how many goroutines run at once?

Use a buffered channel as a semaphore: send before starting work and receive when done. With a capacity of 3, only three goroutines can do the work at the same time. A worker pool is another common answer.

Q10. How do you return an error from a goroutine?

Send it on a channel, or store it in a slot like the results in Program 2. The errgroup package from golang.org/x/sync does this neatly and also cancels the other goroutines on the first error.

Q11. What is a goroutine leak?

It is a goroutine that never ends, usually because it waits forever on a channel nobody uses. Leaks slowly eat memory, so always give goroutines a way to stop.

Q12. When should you not use goroutines?

When the work is tiny, like adding two numbers, the cost of starting and syncing goroutines is bigger than the gain. Also avoid them when every step depends on the previous one.

Practice Task

This task is a small version of real Go goroutine programs. Write a program that checks five website names concurrently by “pinging” each with a fake delay, and prints which ones answered in under 200 ms. Hint: use wg.Go, store each result in its own slot, and print after wg.Wait().

Official Resources

Quick Recap

  • Go goroutine programs start work with go f(), and it runs alongside main.
  • When main returns, all goroutines stop, so wait with a WaitGroup or a channel.
  • wg.Go (Go 1.25+) handles Add, go and Done in one call.
  • Give each goroutine its own result slot, or use a channel or mutex for shared data.
  • A panic in a goroutine crashes the program unless that goroutine recovers.

What’s Next?

Next, goroutines start talking to each other. Read Go channel programs with output, with buffered channels, select, timeouts and producer-consumer. For more on WaitGroup, see Go sync package: WaitGroup and Mutex.