The purpose of this is to test the values of variables which are shared across threads. The test must be protected to ensure no thread modifies the variables during the evaluation of the expression and also that the variables have consistent values.
This is different from Pthreads in which
the thread must explicitly call
pthread_mutex_unlock() and have a call to
pthread_cond_wait() inside the lock. So code here is
Fis returned. Otherwise, if the lock is acquired or
safe = Tand this thread already holds the lock
Tis returned. This is a non-blocking test to acquire the lock. It might be used in the same circumstances in which non-blocking I/O is used in non-threaded applications. However, since we can have multiple threads, it is often more appropriate to have one thread call getLock() and a second thread perform other actions that would have been performed in a single thread if the lock couldn't be acquired immediately. This is often used in optimizing performance where it can be beneficial to recreate data if another thread currently has exclusive access to it. For instance, imagine we have a cache of file/URL contents or images as in a browser. Suppose one thread is performing some modifications to an object that is needed by another thread. If the operation is lengthy relative to the time it takes to obtain a new version of the object (e.g. across the net) then the second thread may attempt to acquire the lock in a non-blocking manner and fail. In this case, it can retrieve the object directly and keep a local copy. Of course, if the second thread requires the modified version of the object that results from the first threads operation, this is not useful. Indeed, more frequently than not, situations in which a non-blocking lock is used can be simplified using a different organizational approach.
The tryGetLock() function can be used to spin in cases where spinning (and polling) is more efficient than being notified of a release of the lock!