TryBugHunt
goAsync race conditionMedium

Goroutines finish before expected despite using sync.WaitGroup

BugFind the bug and fix the code

What it should do

Process a list of tasks concurrently using goroutines. Example: processTasks(tasks) -> [result1, result2,...]

What happens instead

The main function completes execution before all goroutines finish processing their tasks.

package main

import (
	"fmt"
	"sync"
)

func processTask(task string, wg *sync.WaitGroup) string {
	defer wg.Done()	// Simulate processing
	return "Processed " + task
}

func processTasks(tasks []string) []string {
	var wg sync.WaitGroup
	results := make([]string, len(tasks))
	for i, task := range tasks {
		go func(i int, task string) {
			wg.Add(1)		// Incorrect placement
			results[i] = processTask(task, &wg)
		}(i, task)
	}
	wg.Wait()
	return results
}

func main() {
	tasks := []string{"task1", "task2"}
	results := processTasks(tasks)
	fmt.Println(results)
}

Test a custom input to verify an edge case (e.g. empty lists, negative numbers, duplicates).

⏱️0:00
Hints
🏆 0 hints = Flawless Solve
Think & Test Cooldown
2:00 remaining

Take a moment to read the bug symptom and trace the code with Run & Check before unlocking Hint 1.

Hint 2
Unlocks after Hint 1
Hint 3
Unlocks after Hint 2

This bug belongs to the async and race conditions pattern

Goroutines racing on shared data, a WaitGroup used wrong, or a channel that deadlocks.

What you'll practise

A medium Go debugging exercise about async and race conditions: goroutines racing on shared data, a WaitGroup used wrong, or a channel that deadlocks.

The checks your fix must pass

Signs of this kind of bug

Spoiler: why this bug happens(try it first; the hints get warmer one at a time)

What went wrong: The WaitGroup.Add(1) call was inside the goroutine, which led to a race condition where the main goroutine might call Wait() before all goroutines had called Add(1).

The fix: Move the WaitGroup.Add(1) call before launching the goroutine to ensure it is called for each goroutine before they start.

Remember: Always increment the WaitGroup counter before launching a goroutine to avoid race conditions.

The pattern behind it: async and race conditions.

More async and race conditions to practise

Related errors

Embed this challenge on your site

Paste this into any web page or blog post. Visitors fix the bug right there, in their browser.

<iframe src="https://trybughunt.com/embed/b0f003e0-63cb-4785-83bd-fa23f3827133" title="Debugging challenge: Goroutines finish before expected despite using sync.WaitGroup" width="100%" height="580" loading="lazy" style="border:1px solid #d4d4d8;border-radius:12px;max-width:760px"></iframe>
<p style="font-size:14px">Debugging challenge from <a href="https://trybughunt.com/challenges/b0f003e0-63cb-4785-83bd-fa23f3827133">TryBugHunt</a></p>