Sobes.tech
Junior — Middle

Mis täpselt edastatakse või kasutatakse lukustusmehhanismis (lock) mitme lõime programmeerimisel?

sobes.tech AI

Vastus AI-lt

In multithreading lock mechanism, an object or synchronization primitive is used to ensure exclusive access to a shared resource. When a thread acquires the lock, other threads attempting to acquire the same lock will wait until it is released.

That is, under "lock" it is passed or used:

  • The lock state (occupied/free).
  • The waiting mechanism (e.g., a queue of threads waiting for release).

In C#, the lock keyword works with an object that serves as a lock marker. Example:

private readonly object _lockObj = new object();

void CriticalSection()
{
    lock(_lockObj)
    {
        // Code that should be executed by only one thread at a time
    }
}

Here, in lock, a reference to the _lockObj object is passed, which is used to manage access. Internally, CLR uses this object to control the lock state.