- What's a race condition?
A race condition is a situation where an application tries to execute two operations on the same resource at the same time, and the nature of the resource only allows one operation at time. - What happens when you try to execute read and write operations concurrently with a map?
When reading and writing operations on a map happen simultaneously, this causes a runtime error: concurrent map writes. - What's the difference between Mutex and RWMutex?
A regular mutex allows a resource to be locked and unlocked, and each operation has the same priority. A read/write mutex has two types of locks, one for each operation (read/write). The read lock allows more than one operation at time, while it is exclusive. Write locks could be subject to a delay if there are many continuous read operations on the resource. This is known as write starvation. - Why are wait groups useful?
Wait groups are the perfect tool to synchronize with the execution of different goroutines. This enables a clean and elegant solution to the classic setting, where there are several concurrent operations, and a main goroutine has to wait for them to end before moving on. - What's the main use of sync.Once?
sync.Once can be used to execute a concurrent operation on one occasion. It can be used to close a channel once and avoid panics, for instance. Another use case is the lazy initialization of a variable to implement a thread-safe version of the singleton design pattern.
- How can you use a pool?
A pool allows short-lived items to be reused. A good use case for pools is byte slices and byte buffers, because the pool will prevent this resource from being recycled by the garbage collector, while preventing the allocation of new pools. - What's the advantage of using atomic operations?
Using a mutex for numeric variables has a lot of overhead. Atomic operations allow such overheads to be reduced and thread-safe operations to be executed on numeric variables. Its main use is for integer numbers, but, with some transformation, we can do the same for other types, such as Booleans and floats.