Junior — Middle
Kas saaksite selgitada mutexi tööpõhimõtet ja selle kasutamist mitmetuumalistes programmides?
sobes.tech AI
Vastus AI-lt
Mutual exclusion (Mutex) is a synchronization mechanism used to prevent multiple threads from simultaneously accessing a shared resource (such as a variable or a file). Mutex guarantees that at any given moment, only one thread can hold the lock and execute the critical section of code.
Working principle:
- The thread attempts to acquire the mutex before entering the critical section.
- If the mutex is free, the thread gains access and continues.
- If the mutex is occupied by another thread, the current thread is blocked and waits for it to be released.
- After finishing with the resource, the thread releases the mutex, allowing other threads to continue.
In Go, this is implemented via the sync.Mutex type:
var mu sync.Mutex
var counter int
func increment() {
mu.Lock() // acquire mutex
counter++ // critical section
mu.Unlock() // release mutex
}
Using mutex prevents race conditions and ensures data integrity during parallel execution.