GO Goroutines and Concurrency 1 — Questions and Answers
Question 1: What keyword is used to start a goroutine in Go?
- go (Correct answer)
- goroutine
- async
- spawn
Correct answer: go
The `go` keyword before a function call launches it as a goroutine, running concurrently with other goroutines.
Question 2: What is the primary purpose of the `sync.WaitGroup` in Go?
- Limit goroutine count
- Wait for a collection of goroutines to finish (Correct answer)
- Share data between goroutines
- Cancel goroutine execution
Correct answer: Wait for a collection of goroutines to finish
`sync.WaitGroup` blocks the calling goroutine until all goroutines tracked via `Add`, `Done`, and `Wait` have completed.
Question 3: Which package provides the `Mutex` type for protecting shared state in Go?
- os
- sync (Correct answer)
- runtime
- atomic
Correct answer: sync
The `sync` package provides `Mutex` and `RWMutex` for safe concurrent access to shared data.
Question 4: What happens when a goroutine panics and the panic is not recovered?
- Only that goroutine exits
- The panic is silently ignored
- The entire program crashes (Correct answer)
- Other goroutines are notified
Correct answer: The entire program crashes
An unrecovered panic in any goroutine terminates the entire Go program, not just that goroutine.
Question 5: Which function returns the number of logical CPUs available to the current process?
- runtime.NumCPU() (Correct answer)
- runtime.GOMAXPROCS(0)
- os.NumCPU()
- sync.NumCPU()
Correct answer: runtime.NumCPU()
`runtime.NumCPU()` returns the number of logical CPUs on the machine, while `GOMAXPROCS` sets/gets the limit used by the scheduler.
Question 6: What does `runtime.GOMAXPROCS(n)` do when called with `n > 1`?
- Limits goroutine stack size
- Sets the maximum number of OS threads executing Go code simultaneously (Correct answer)
- Increases goroutine priority
- Disables the garbage collector
Correct answer: Sets the maximum number of OS threads executing Go code simultaneously
`runtime.GOMAXPROCS(n)` sets the maximum number of OS threads that can execute user-level Go code simultaneously, enabling true parallelism.
What keyword is used to start a goroutine in Go?