Junior — Middle
Can you explain the mechanism of locks in multithreaded programs?
sobes.tech AI
Answer from AI
In multithreaded programs, locks are used to control access to shared resources to prevent race conditions and ensure data correctness.
The locking mechanism is usually based on a synchronization object (e.g., lock in C#), which allows one thread to acquire the lock, while others wait until it is released.
Example of using lock in C#:
private readonly object _lockObj = new object();
void UpdateResource() {
lock(_lockObj) {
// Code inside this block can only be executed by one thread at a time
// Here, it is safe to modify shared resources
}
}
When a thread enters the lock block, it acquires the lock. If another thread tries to enter, it will wait until the first thread exits and releases the lock.
This prevents concurrent access to critical sections and ensures data consistency.
It is important to avoid deadlocks, where two or more threads wait for each other, holding different locks.