Junior — Middle
Kas saaksite selgitada, millised lukustamise tüübid on olemas ja kuidas need töötavad mitme lõimega programmeerimisel?
sobes.tech AI
Vastus AI-lt
Multithread programming involves different types of locks that help synchronize access to shared resources:
- Mutex (Mutual Exclusion) — ensures exclusive access to a resource. Only one thread can acquire the mutex at a time.
- Recursive mutex — allows the same thread to acquire the lock multiple times without mutual blocking.
- Read-Write Lock — allows multiple threads to read the resource simultaneously, but writing is only possible exclusively.
- Semaphore — limits the number of threads that can access the resource at the same time.
- Spinlock (active waiting) — the thread checks in a loop whether the lock is available, without entering a waiting state.
Example of using a mutex in Swift:
let lock = NSLock()
func criticalSection() {
lock.lock()
// Critical section
lock.unlock()
}
The choice of lock type depends on the task and performance and security requirements.