GO Goroutines and Concurrency 2 — Questions and Answers
Question 1: What is a race condition in Go?
- Two goroutines finishing at the same time
- Two goroutines accessing shared memory without proper synchronization (Correct answer)
- A goroutine running faster than expected
- Deadlock caused by channel blocking
Correct answer: Two goroutines accessing shared memory without proper synchronization
A race condition occurs when two or more goroutines access shared memory concurrently and at least one access is a write, without synchronization.
Question 2: How do you detect race conditions when running Go tests?
- go test -verbose
- go test -race (Correct answer)
- go test -sync
- go test -concurrent
Correct answer: go test -race
The `-race` flag enables Go's built-in race detector, which instruments the code to report data races at runtime.
Question 3: Which `sync` type allows multiple concurrent readers but only one writer at a time?
- sync.Mutex
- sync.RWMutex (Correct answer)
- sync.Once
- sync.Cond
Correct answer: sync.RWMutex
`sync.RWMutex` provides `RLock`/`RUnlock` for multiple concurrent readers and `Lock`/`Unlock` for exclusive write access.
Question 4: What is the purpose of `sync.Once`?
- Run a goroutine exactly once
- Lock a mutex once and never unlock
- Execute a function exactly one time across all goroutines (Correct answer)
- Prevent goroutine reuse
Correct answer: Execute a function exactly one time across all goroutines
`sync.Once` guarantees that a function is executed exactly once, regardless of how many goroutines call `Do`, making it ideal for initialization.
Question 5: What does the Go scheduler use as its concurrency model?
- One OS thread per goroutine
- M:N threading (many goroutines on fewer OS threads) (Correct answer)
- Single-threaded event loop
- Actor model
Correct answer: M:N threading (many goroutines on fewer OS threads)
Go uses an M:N scheduler that multiplexes many goroutines (M) onto a smaller number of OS threads (N), managed by the Go runtime.
Question 6: Which function yields the processor, allowing other goroutines to run?
- runtime.Sleep()
- runtime.Gosched() (Correct answer)
- runtime.Yield()
- runtime.Pause()
Correct answer: runtime.Gosched()
`runtime.Gosched()` yields the CPU to allow other goroutines to run but does not block the current goroutine.
What is a race condition in Go?