Sobes.tech
Senior

If RLock is used in AddTask, how will two parallel calls to AddTask behave? Will they block each other?

sobes.tech AI

Answer from AI

In Go, sync.RWMutex provides two types of locks: RLock for reading and Lock for writing.

If the AddTask function uses RLock (i.e., a read lock), then two parallel calls to AddTask can acquire RLock simultaneously and execute in parallel without blocking each other.

However, if somewhere in the code Lock (a write lock) is used, it will wait until all RLocks are released, and vice versa — new RLocks will wait until Lock is released.

Thus, two calls to AddTask with RLock do not block each other, but if data modification occurs inside AddTask, using RLock is incorrect and can lead to data races.

Example:

var mu sync.RWMutex

func AddTask() {
    mu.RLock()         // read lock
    defer mu.RUnlock()
    // read data
}

Two calls to AddTask can execute simultaneously.

If RLock is used in AddTask, how will two parallel… - sobes.tech