0
0
Goprogramming~20 mins

Why concurrency is needed in Go - Challenge Your Understanding

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Concurrency Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of concurrent goroutines
What is the output of this Go program that launches two goroutines printing numbers?
Go
package main
import (
	"fmt"
	"time"
)
func main() {
	go func() {
		for i := 1; i <= 3; i++ {
			fmt.Print(i)
			time.Sleep(10 * time.Millisecond)
		}
	}()
	go func() {
		for i := 4; i <= 6; i++ {
			fmt.Print(i)
			time.Sleep(10 * time.Millisecond)
		}
	}()
	time.Sleep(50 * time.Millisecond)
}
A123456
BAny interleaved combination of digits 1 to 6
C456123
DProgram does not print anything
Attempts:
2 left
💡 Hint
Think about how goroutines run independently and may print in any order.
🧠 Conceptual
intermediate
1:30remaining
Why use concurrency in Go?
Which of the following best explains why concurrency is needed in Go programs?
ATo prevent any code from running in parallel
BTo make programs run slower and use more memory
CTo avoid using functions and loops
DTo allow multiple tasks to run at the same time improving efficiency and responsiveness
Attempts:
2 left
💡 Hint
Think about how computers can do many things at once.
🔧 Debug
advanced
2:30remaining
Identify the concurrency issue
What error or problem will this Go code cause when run?
Go
package main
import (
	"fmt"
)
func main() {
	for i := 0; i < 3; i++ {
		go func(i int) {
			fmt.Println(i)
		}(i)
	}
	// Wait for goroutines
	var input string
	fmt.Scanln(&input)
}
APrints 0, 1, 2 as expected
BCompilation error due to missing import
CPrints 3, 3, 3 because of variable capture in goroutine
DDeadlock error at runtime
Attempts:
2 left
💡 Hint
Think about how the loop variable is used inside the goroutine.
📝 Syntax
advanced
1:30remaining
Identify the syntax error in concurrency code
Which option contains a syntax error in Go concurrency code?
Ago func() { fmt.Println("Hello") }
B)(} )"olleH"(nltnirP.tmf { )(cnuf og
Cgo func() { fmt.Println("Hello") }()
Do func() { fmt.Println("Hello") }()
Attempts:
2 left
💡 Hint
Check if the anonymous function is called immediately.
🚀 Application
expert
3:00remaining
How many goroutines run concurrently?
Given this Go program, how many goroutines run concurrently at peak?
Go
package main
import (
	"fmt"
	"time"
)
func worker(id int) {
	fmt.Printf("Worker %d starting\n", id)
	time.Sleep(50 * time.Millisecond)
	fmt.Printf("Worker %d done\n", id)
}
func main() {
	for i := 1; i <= 5; i++ {
		go worker(i)
	}
	time.Sleep(100 * time.Millisecond)
}
ANo goroutines run concurrently
B1 goroutine at a time
C5 goroutines run concurrently
D10 goroutines run concurrently
Attempts:
2 left
💡 Hint
Count how many goroutines are started and how long they run.