It's well known that synchronous processing is necessary for multithreaded programming. The operating system provides some basic way, such as critical section, mutex. However, those methods are not enough for large systems. I present three locks that can provide higher performance.
Recursive lock
It can be acquired repeatedly by the thread holding the lock. And that will not result in deadlock. There must be a unlock operation corresponding to each lock operation in the thread holding the lock so that the other thread can acquire it. It's useful in the scenario that a thread may acquire a lock many times, especially in the recursive functions. However, it's slower than non-recursive lock.
Spin lock
The waiting thread doesn't block at the synchronizing point, but "spins" to try to acquire the lock. Spinlocks do have a advantage in that no context switch is required when a thread must wait on a lock, and a context switch may take considerable time. Thus, when locks are expected to be held for short times, spinlocks are useful. They are often employed on multiprocessor systems where one thread can "spin" on one processor while another thread run on another processor. Note that misuse of it may reulst in thread starvation. It can be solved by queuing the waiting threads.
Read and write lock
It is also called as multiple read/single-write lock. It permit multiple thread to read the shared resources concurrently, while only one thread can be authorised to perform write operation at most. It's a high performance mechanism for those applications which multiple threads may often read the shared resources at the same time and the write operation is performed less times. Well for long shared data, it's desirable to divide it into more segments to use read-write lock for synchronizing.
The code is shown as follow: