Junior
What is a mutex?
sobes.tech AI
Answer from AI
Mutex (mutual exclusion) is a synchronization mechanism used to protect a shared resource from concurrent access by multiple threads (or processes). At any given moment, only one thread can own the mutex and, consequently, access the protected resource.
Main operations with mutex:
- lock: Attempt to acquire ownership of the mutex. If the mutex is free, the thread acquires it and continues execution. If the mutex is already occupied by another thread, the current thread is blocked until the mutex is released.
- unlock: Release ownership of the mutex. This allows another waiting thread to acquire it. It is important that the mutex is released by the same thread that acquired it.
For example, in Objective-C or Swift, you can use NSLock to work with mutexes.
Example of using NSLock in Objective-C:
// Objective-C
#import <Foundation/Foundation.h>
@interface MyClass : NSObject {
NSLock *_lock;
int _sharedResource;
}
@end
@implementation MyClass
- (instancetype)init {
self = [super init];
if (self) {
_lock = [[NSLock alloc] init];
_sharedResource = 0;
}
return self;
}
- (void)updateSharedResource {
[_lock lock]; // Acquire the mutex
@try {
// Work with _sharedResource - critical section
_sharedResource++;
NSLog(@"Shared resource updated to %d by thread %@", _sharedResource, [NSThread currentThread]);
}
@finally {
[_lock unlock]; // Release the mutex
}
}
@end
Example of using NSLock in Swift:
// Swift
import Foundation
class MyClass {
private let lock = NSLock()
private var sharedResource = 0
func updateSharedResource() {
lock.lock() // Acquire the mutex
// Work with sharedResource - critical section
sharedResource += 1
print("Shared resource updated to \(sharedResource) by thread \(Thread.current)")
lock.unlock() // Release the mutex
}
}
Mutexes prevent race conditions and ensure data integrity during parallel access. Incorrect use of mutexes can lead to deadlocks.