0
0
Goprogramming~20 mins

Goroutine creation - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Goroutine Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of simple goroutine execution
What is the output of this Go program?
Go
package main
import (
	"fmt"
	"time"
)
func main() {
	go fmt.Println("Hello from goroutine")
	time.Sleep(100 * time.Millisecond)
	fmt.Println("Main function finished")
}
A
Hello from goroutine
Main function finished
B
Main function finished
Hello from goroutine
CHello from goroutine
DMain function finished
Attempts:
2 left
💡 Hint
Think about how goroutines run concurrently and why we use Sleep here.
Predict Output
intermediate
2:00remaining
Goroutine variable capture behavior
What will be printed by this Go program?
Go
package main
import (
	"fmt"
	"time"
)
func main() {
	for i := 0; i < 3; i++ {
		go func() {
			fmt.Println(i)
		}()
	}
	time.Sleep(100 * time.Millisecond)
}
A
3
3
3
B
0
1
2
C
0
0
0
D
2
2
2
Attempts:
2 left
💡 Hint
Consider how the loop variable is captured by the goroutine function.
🔧 Debug
advanced
2:00remaining
Identify the error in goroutine creation
What error will this Go program produce when run?
Go
package main
func main() {
	go func() {
		println("Running")
	}()
}
ARuntime panic: goroutine not started
BSyntax error: missing import fmt
CDeadlock detected
DNo output, program exits immediately
Attempts:
2 left
💡 Hint
Think about what happens to the main function after starting a goroutine.
Predict Output
advanced
2:00remaining
Goroutine with argument capture
What is the output of this Go program?
Go
package main
import (
	"fmt"
	"time"
)
func main() {
	for i := 0; i < 3; i++ {
		go func(n int) {
			fmt.Println(n)
		}(i)
	}
	time.Sleep(100 * time.Millisecond)
}
A
2
2
2
B
3
3
3
C
0
1
2
D
0
0
0
Attempts:
2 left
💡 Hint
Look at how the loop variable is passed as an argument to the goroutine function.
🧠 Conceptual
expert
2:00remaining
Goroutine scheduling and output order
Given this Go program, which output is guaranteed?
Go
package main
import (
	"fmt"
	"sync"
)
func main() {
	var wg sync.WaitGroup
	wg.Add(2)
	go func() {
		defer wg.Done()
		fmt.Println("First")
	}()
	go func() {
		defer wg.Done()
		fmt.Println("Second")
	}()
	wg.Wait()
}
A
First
Second
BEither "First\nSecond" or "Second\nFirst"
C
Second
First
DNo output
Attempts:
2 left
💡 Hint
Consider how goroutines are scheduled and the use of WaitGroup.