Sleep(1) 是 Windows 中记录的让处理器让出并允许其他线程运行的方法。您可以在带有注释的参考源中找到此代码:
// Our memory model guarantee if we pick up the change in bucket from another processor,
// we will see the 'isWriterProgress' flag to be true or 'version' is changed in the reader.
//
int spinCount = 0;
do {
// this is violate read, following memory accesses can not be moved ahead of it.
currentversion = version;
b = lbuckets[bucketNumber];
// The contention between reader and writer shouldn't happen frequently.
// But just in case this will burn CPU, yield the control of CPU if we spinned a few times.
// 8 is just a random number I pick.
if( (++spinCount) % 8 == 0 ) {
Thread.Sleep(1); // 1 means we are yeilding control to all threads, including low-priority ones.
}
} while ( isWriterInProgress || (currentversion != version) );
isWriterInProgress 变量是一个 volatile bool。作者在英文“violate read”是“volatile read”时遇到了一些麻烦。基本思想是尽量避免让步,线程上下文切换非常昂贵,希望作者能快速完成。如果那没有成功,那么显式让步以避免烧毁 CPU。这可能是今天用 Spinlock 编写的,但 Hashtable 已经很老了。关于内存模型的假设也是如此。