Sobes.tech
Junior — Middle

Selgitage, mis on lukustus (Lock) mutexi kontekstis ja milleks seda kasutatakse.

sobes.tech AI

Vastus AI-lt

Lock is a synchronization mechanism used to prevent multiple threads or goroutines from accessing a shared resource simultaneously, to avoid race conditions and ensure data correctness.

In the context of a mutex, locking means that when one thread acquires (locks) a mutex, other threads attempting to acquire the same mutex will wait until the first thread releases (unlocks) it.

Example in Go:

var mu sync.Mutex
var counter int

func increment() {
    mu.Lock()         // acquire the lock
    counter++         // critical section
    mu.Unlock()       // release the lock
}

This way, the lock guarantees that only one thread executes the critical section of the code at a given time.