可以使用互斥锁和信号量模拟读者/写者锁。如果每秒需要访问数千次,我不会这样做,但是每秒数十次或数百次,它应该可以正常工作。
这个锁将允许一个作者的独占访问,或者允许N个(可能很多,但需要定义)读者的并发访问。
这是如何工作的。我将以10个读者为例。
初始化一个命名互斥锁,起初未发出信号,并且带有10个插槽的命名信号量。
Mutex m = new Mutex(false, "MyMutex");
Semaphore s = new Semaphore(10, 10, "MySemaphore");
获取读取锁定:
// Lock access to the semaphore.
m.WaitOne();
// Wait for a semaphore slot.
s.WaitOne();
// Release mutex so others can access the semaphore.
m.ReleaseMutex();
释放读取锁定:
s.Release();
获取写锁:
// Lock access to the seamphore
m.WaitOne();
// Here we re waiting for the semaphore to get full,
// meaning that there aren t any more readers accessing.
// The only way to get the count is to call Release.
// So we wait, then immediately release.
// Release returns the previous count.
// Since we know that access to the semaphore is locked
// (i.e. nobody can get a slot), we know that when count
// goes to 9 (one less than the total possible), all the readers
// are done.
s.WaitOne();
int count = s.Release();
while (count != 9)
{
// sleep briefly so other processes get a chance.
// You might want to tweak this value. Sleep(1) might be okay.
Thread.Sleep(10);
s.WaitOne();
count = s.Release();
}
// At this point, there are no more readers.
释放写锁:
m.ReleaseMutex();
尽管它很脆弱(每个使用该信号量计数的过程都应该相同!),但我认为只要你不试图过度使用它,它就会做你想要的。