suppose we have this next sample code:
while(some condition){
lock1.lock();
.
.
}
the question is:
suppose the condition of the while loop is exiting for some thread that run’s over this code part and lock1 is available, is it possible that the thread will check the condition of the loop but still won’t get the lock?
or is it guaranteed in this case that if the condition is checked the thread gets the lock?
In short: Yes, it is possible.
If another thread has already acquired the lock, then your thread will be forced to wait for it to become free.
Remember that you have no way of knowing how two or more concurrently executing threads interleave their instruction executions. Assume two threads, A and B, execute this code. If thread A finds the condition true, it is possible that it gets preempted (taken off the CPU by the OS scheduler) before actually acquiring the lock (that is, between evaluating the while condition and the call to
lock()), so thread B also finds the condition true, takes the lock and thread A is left waiting.