I recently read the book "Art of multi-processor programming" and the English version. Recently, I found that the quality of the Chinese translation version of technical books is getting worse and worse, and many translators simply pay for it, in fact, they are mostly white in the IT field, so let's take a look at the original English version. Although it is a bit powerful, it is at least accurate. I used the time on the subway to read the spin lock chapter, and I felt very rewarding.
In fact, spin locks are meaningless on a single processor rather than a preemptible OS. They only make sense on a multi-processor. The simplest spin locks are the ones that are randomly snatched, however, threads running on all processors wait for the same variable, which will refresh the cache of all competing locks. Therefore, the designer designs a new spin lock, each thread spin on the variable of the current processor. This will not cause all processors to refresh the cache. the first implementation of the spin lock in this version is the array lock. However, the array is statically allocated, if there are few threads competing for the lock, it will lead to a waste of space. Therefore, the second implementation is the queue lock, and the queue is dynamically scalable as needed. Therefore, the problem in the first implementation is solved. Although this new spin lock avoids cache refresh and space waste, it can cause hunger, the runners behind the queue may lose their response because of the long queue time. Therefore, a lock with a timeout value is generated, which avoids the long-term spin of the spin lock, in short, as long as the queue of the spin lock queue is too long, it may lead to hunger. Is there any way to limit the length of the queue? Of course, there are some. This is a composite lock, which balances the advantages of timeout locks and queuing locks, and adds a new concept of contention, which is similar to a token, that is to say, only the thread that obtains the token can wait in line to compete for the spin lock. The number of tokens is limited, so the length of the queue is limited. If a thread obtains the token but the queue times out, then it will discard the token and throw an exception. The caller determines the next action. But wait a moment to see if there is any problem with this lock. It was originally meant to compete for the spin lock and now it has become a token. What is the significance of this? In fact, the purpose of competing for the token is to make the lock more fair, to avoid hunger, it is necessary to break the first-come-first-served process to avoid hunger. The process of competing for a token is to break the first-come-first-served process.AlgorithmIn order not to overhead the token. If you do not consider fairness on the basis of avoiding the hunger timeout lock, the timeout lock is good, but the composite lock further enhances the fairness, this kind of fairness is achieved by breaking the rule first.