Suppose thread 1 tries to acquire a lock on the lockObj object using the lock(lockObj)
statement, but this object is already locked by thread 2 at the moment thread 1 tries to acquire a lock on it. Thread 1 will block, right?
Now suppose that during this blocking, there is a context switch, because there are other threads and applications waiting to run. Is the elapsed time until thread 1 is on Running state again and able to acquire the lock dependent on the OS timer resolution (Ex: default 15.6 ms on Windows 7)?
If the answer to the above question is YES, then I have another doubt:
It is easy to create a simple program to test the average overhead of Thread.Sleep(1)
using Stopwatch and conclude that it converges to the OS timer resolution (15.6 ms, for instance). But I'm finding it hard to create a program to obtain the same conclusion for a lock statement. Mainly because:
1) It is difficult to ensure that the thread trying to acquire the lock will always block (or at least to know WHEN it has blocked before acquiring the lock);
2) I don't know how to force a context switch whenever the thread trying to acquire the lock blocks. Is there ALWAYS a context switch when the current running thread blocks?
Any help will be appreciated.