Goroutines, channels, select, context, sync
Practise these as flashcards. One or two lines each; the ones you miss come back first.
Start freeA goroutine is a lightweight thread managed by the Go runtime, allowing functions to run concurrently. You start a goroutine by prefixing a function call with the go keyword, like go myFunc().
An unbuffered channel blocks the sender until a receiver is ready, ensuring synchronous communication. A buffered channel allows sending up to its capacity without blocking, enabling asynchronous communication between goroutines.
You can use the select statement with a time.After channel to implement a timeout. For example, select { case v := <-ch: ...; case <-time.After(time.Second): ... } will wait for either a value or a timeout.
sync.WaitGroup do?sync.WaitGroup is used to wait for a collection of goroutines to finish. You call Add before starting goroutines, Done in each goroutine when it completes, and Wait to block until all have finished.
select statement do in Go?select lets you wait on multiple channel operations, proceeding with whichever is ready first. It's useful for implementing timeouts, multiplexing, and handling multiple concurrent events.
The Go scheduler uses a work-stealing algorithm to multiplex thousands of goroutines onto a smaller set of OS threads. It manages goroutine states and schedules them based on availability of threads and I/O, allowing efficient concurrent execution.
Buffered channels are useful when you want to decouple the sender and receiver, allowing the sender to proceed without blocking until the buffer is full. This is common in producer-consumer scenarios or when batching messages for efficiency.
context.Context to cancel a long-running goroutine?You pass a context.Context to the goroutine, and inside the goroutine, you check <-ctx.Done() or ctx.Err() to detect cancellation. When you call the cancel function, the goroutine can exit early, preventing leaks.
sync.Once?sync.Once ensures that a particular function is executed only once, even if called from multiple goroutines. It's typically used for one-time initialization, like setting up a singleton resource.
You should ensure that all worker goroutines have a way to exit, typically by closing the work channel or sending a cancellation signal via context. Properly draining channels and handling context cancellation prevents leaks.
The race detector (go run -race) identifies data races at runtime by tracking variable accesses and reporting conflicts. It helps catch subtle concurrency bugs that can lead to unpredictable behavior.
You use http.Server.Shutdown with a context to allow in-flight requests to complete before the server stops. Typically, you listen for OS signals, then call Shutdown to start the graceful shutdown process.
sync.Mutex could cause a deadlock, and how would you avoid it?