我已经使用来自Windows Via C/C++的代码在 Windows 7 下测试了超薄读写器锁的性能。
结果让我感到惊讶的是,独占锁定性能比共享锁定性能好。这是代码和结果。
unsigned int __stdcall slim_reader_writer_exclusive(void *arg)
{
//SRWLOCK srwLock;
//InitializeSRWLock(&srwLock);
for (int i = 0; i < 1000000; ++i) {
AcquireSRWLockExclusive(&srwLock);
g_value = 0;
ReleaseSRWLockExclusive(&srwLock);
}
_endthreadex(0);
return 0;
}
unsigned int __stdcall slim_reader_writer_shared(void *arg)
{
int b;
for (int i = 0; i < 1000000; ++i) {
AcquireSRWLockShared(&srwLock);
//b = g_value;
g_value = 0;
ReleaseSRWLockShared(&srwLock);
}
_endthreadex(0);
return 0;
}
g_value
是一个全局 int volatile 变量。
你能解释一下为什么会发生这种情况吗?