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变量是易失性布尔值.笔者在英语中遇到了一些麻烦,"违规阅读"是"易失性阅读".基本的 idea 是尽量避免让步,线程上下文切换是非常昂贵的,希望作者能尽快完成.如果这不起作用,那么显式让步以避免消耗CPU.这可能是今天用Spinlock写的,但是Hashtable已经很旧了.关于内存模型的假设也是如此.