Concurrency Quiz - Languages Golang
Free practice quiz: Concurrency (Languages Golang). 52 multiple-choice questions with answers and explanations. Play online, no sign-up needed.
Play all 52 questions freeSample questions
In Go, what is the primary mechanism for achieving concurrency?
- Threads and Locks
- Goroutines and Channels
- Processes and Message Queues
- Async/Await patterns
Show answer
Answer: B. Goroutines and Channels
Go's concurrency model is built around lightweight, independently executing functions called goroutines, and a powerful communication mechanism called channels, which are used for safe data exchange between goroutines.
When using unbuffered channels in Go, what is the behavior of a send operation?
- It succeeds immediately and returns
- It blocks until a receiving goroutine is ready to receive the value
- It is placed in a buffer and continues immediately
- It causes a panic if no receiver is ready
Show answer
Answer: B. It blocks until a receiving goroutine is ready to receive the value
Unbuffered channels require both the sender and receiver to be ready simultaneously for a communication to occur. This is known as rendezvous.
In Go, what is the `nil` channel behavior when used with `select`?
- A `select` statement with a `nil` channel case will never be chosen
- A `select` statement with a `nil` channel case will always be chosen
- A `select` statement with a `nil` channel case will cause a panic
- A `select` statement with a `nil` channel case will block indefinitely if other cases are also blocked
Show answer
Answer: A. A `select` statement with a `nil` channel case will never be chosen
Receive or send operations on a `nil` channel block forever. Therefore, a `select` statement that includes a case involving a `nil` channel will never proceed on that case if there are other valid (non-`nil`) cases available. If all cases are `nil` or blocked, the `select` will block.
Consider a scenario where multiple goroutines are writing to the same `map[string]int`. What is the most appropriate way to ensure thread safety?
- Use a `sync.WaitGroup` to coordinate the goroutines.
- Use a `sync.RWMutex` to protect the map.
- Use a buffered channel to send map updates.
- Use `sync.Once` to initialize the map.
Show answer
Answer: B. Use a `sync.RWMutex` to protect the map.
Maps in Go are not inherently safe for concurrent read/write access. A `sync.RWMutex` is ideal here because it allows multiple readers to access the map concurrently, while writes are exclusive. A regular `sync.Mutex` would also work but would be less performant if reads are frequent.
Which Go package provides synchronization primitives like Mutexes, WaitGroups, and Once?
- fmt
- net/http
- sync
- context
Show answer
Answer: C. sync
The `sync` package in Go's standard library offers essential primitives for building concurrent programs, including `Mutex`, `RWMutex`, `WaitGroup`, `Once`, `Cond`, and `Pool`.