Go

Sync Primitives

sync.Mutex, RWMutex, Once, Pool, Map, Cond, atomic operations

22 câu hỏi phỏng vấn·
Mid-Level
1

What is a sync.Mutex in Go?

Câu trả lời

A sync.Mutex (mutual exclusion lock) is a synchronization primitive that ensures only one goroutine can access a critical section at a time. Calling Lock blocks until the mutex is available, and Unlock releases it for other goroutines. Use it to protect concurrent access to shared data.

2

What happens if we forget to call Unlock after Lock on a sync.Mutex?

Câu trả lời

Forgetting Unlock creates a potential deadlock as other goroutines will wait indefinitely to acquire the mutex. The best practice is to use defer to ensure Unlock will be called even in case of panic. Always pair Lock and Unlock in the same scope to avoid lock leaks.

3

What is the main difference between sync.Mutex and sync.RWMutex?

Câu trả lời

The sync.RWMutex allows multiple concurrent reads via RLock but only one exclusive write via Lock. This improves performance for read-heavy scenarios as readers don't block each other. Use RWMutex when reads are frequent and writes are rare.

4

Why use defer with Unlock on a sync.Mutex?

5

When to prefer sync.RWMutex over sync.Mutex?

+19 câu hỏi phỏng vấn

Nắm vững Go cho lần phỏng vấn tiếp theo

Truy cập tất cả câu hỏi, flashcards, bài kiểm tra kỹ thuật, bài tập code review và mô phỏng phỏng vấn.

Bắt đầu miễn phí