读写锁实际是一种特殊的自旋锁,它把对共享资源的访问者划分成读者和写者,读者只对共享资源进行读访问,写者则需要对共享资源进行写操作。这种锁相对于自旋锁而言,能提高并发性,因为在多处理器系统中,它允许同时有多个读者来访问共享资源,最大可能的读者数为实际的逻辑CPU数。写者是排他性的,一个读写锁同时只能有一个写者或多个读者(与CPU数相关),但不能同时既有读者又有写者。
在读写锁保持期间也是抢占失效的。
如果读写锁当前没有读者,也没有写者,那么写者可以立刻获得读写锁,否则它必须自旋在那里,直到没有任何写者或读者。如果读写锁没有写者,那么读者可以立即获得该读写锁,否则读者必须自旋在那里,直到写者释放该读写锁。
1. 特性:
一次只有一个线程可以占有写模式的读写锁, 但是可以有多个线程同时占有读模式的读写锁. 正是因为这个特性,
当读写锁是写加锁状态时, 在这个锁被解锁之前, 所有试图对这个锁加锁的线程都会被阻塞.
当读写锁在读加锁状态时, 所有试图以读模式对它进行加锁的线程都可以得到访问权, 但是如果线程希望以写模式对此锁进行加锁, 它必须直到所有的线程释放锁.
通常, 当读写锁处于读模式锁住状态时, 如果有另外线程试图以写模式加锁, 读写锁通常会阻塞随后的读模式锁请求, 这样可以避免读模式锁长期占用, 而等待的写模式锁请求长期阻塞.
2. 适用性:
RWLockImpl.cpp
下边是测试代码
在读写锁保持期间也是抢占失效的。
如果读写锁当前没有读者,也没有写者,那么写者可以立刻获得读写锁,否则它必须自旋在那里,直到没有任何写者或读者。如果读写锁没有写者,那么读者可以立即获得该读写锁,否则读者必须自旋在那里,直到写者释放该读写锁。
1. 特性:
一次只有一个线程可以占有写模式的读写锁, 但是可以有多个线程同时占有读模式的读写锁. 正是因为这个特性,
当读写锁是写加锁状态时, 在这个锁被解锁之前, 所有试图对这个锁加锁的线程都会被阻塞.
当读写锁在读加锁状态时, 所有试图以读模式对它进行加锁的线程都可以得到访问权, 但是如果线程希望以写模式对此锁进行加锁, 它必须直到所有的线程释放锁.
通常, 当读写锁处于读模式锁住状态时, 如果有另外线程试图以写模式加锁, 读写锁通常会阻塞随后的读模式锁请求, 这样可以避免读模式锁长期占用, 而等待的写模式锁请求长期阻塞.
2. 适用性:
读写锁适合于对数据结构的读次数比写次数多得多的情况. 因为, 读模式锁定时可以共享, 以写模式锁住时意味着独占, 所以读写锁又叫共享-独占锁。
现在Win32的API,用C++实现自己的读写锁。这组API包括:CreateMutex,CreateEvent,WaitForSingleObject,WaitForMultipleObjects,ResetEvent,ReleaseMutex,SetEvent,CloseHandle。以下代码在VS2005下,已经编译通过。
RWLockImpl.h
- #ifndef _RWLockImpl_Header
- #define _RWLockImpl_Header
- #include <assert.h>
- #include <iostream>
- #include <Windows.h>
- #include <process.h>
- using namespace std;
- /*
- 读写锁允许当前的多个读用户访问保护资源,但只允许一个写读者访问保护资源
- */
- //-----------------------------------------------------------------
- class CRWLockImpl
- {
- protected:
- CRWLockImpl();
- ~CRWLockImpl();
- void ReadLockImpl();
- bool TryReadLockImpl();
- void WriteLockImpl();
- bool TryWriteLockImpl();
- void UnlockImpl();
- private:
- void AddWriter();
- void RemoveWriter();
- DWORD TryReadLockOnce();
- HANDLE m_mutex;
- HANDLE m_readEvent;
- HANDLE m_writeEvent;
- unsigned m_readers;
- unsigned m_writersWaiting;
- unsigned m_writers;
- };
- //-----------------------------------------------------------------
- class CMyRWLock: private CRWLockImpl
- {
- public:
- //创建读/写锁
- CMyRWLock(){};
- //销毁读/写锁
- ~CMyRWLock(){};
- //获取读锁
- //如果其它一个线程占有写锁,则当前线程必须等待写锁被释放,才能对保护资源进行访问
- void ReadLock();
- //尝试获取一个读锁
- //如果获取成功,则立即返回true,否则当另一个线程占有写锁,则返回false
- bool TryReadLock();
- //获取写锁
- //如果一个或更多线程占有读锁,则必须等待所有锁被释放
- //如果相同的一个线程已经占有一个读锁或写锁,则返回结果不确定
- void WriteLock();
- //尝试获取一个写锁
- //如果获取成功,则立即返回true,否则当一个或更多其它线程占有读锁,返回false
- //如果相同的一个线程已经占有一个读锁或写锁,则返回结果不确定
- bool TryWriteLock();
- //释放一个读锁或写锁
- void Unlock();
- private:
- CMyRWLock(const CMyRWLock&);
- CMyRWLock& operator = (const CMyRWLock&);
- };
- inline void CMyRWLock::ReadLock()
- {
- ReadLockImpl();
- }
- inline bool CMyRWLock::TryReadLock()
- {
- return TryReadLockImpl();
- }
- inline void CMyRWLock::WriteLock()
- {
- WriteLockImpl();
- }
- inline bool CMyRWLock::TryWriteLock()
- {
- return TryWriteLockImpl();
- }
- inline void CMyRWLock::Unlock()
- {
- UnlockImpl();
- }
- #endif
- #include "RWLockImpl.h"
- CRWLockImpl::CRWLockImpl(): m_readers(0), m_writersWaiting(0), m_writers(0)
- {
- m_mutex = CreateMutex(NULL, FALSE, NULL);
- if (m_mutex == NULL)
- cout<<"cannot create reader/writer lock"<<endl;
- m_readEvent = CreateEvent(NULL, TRUE, TRUE, NULL);
- if (m_readEvent == NULL)
- cout<<"cannot create reader/writer lock"<<endl;
- m_writeEvent = CreateEvent(NULL, TRUE, TRUE, NULL);
- if (m_writeEvent == NULL)
- cout<<"cannot create reader/writer lock"<<endl;
- }
- CRWLockImpl::~CRWLockImpl()
- {
- CloseHandle(m_mutex);
- CloseHandle(m_readEvent);
- CloseHandle(m_writeEvent);
- }
- inline void CRWLockImpl::AddWriter()
- {
- switch (WaitForSingleObject(m_mutex, INFINITE))
- {
- case WAIT_OBJECT_0:
- if (++m_writersWaiting == 1)
- ResetEvent(m_readEvent);
- ReleaseMutex(m_mutex);
- break;
- default:
- cout<<"cannot lock reader/writer lock"<<endl;
- }
- }
- inline void CRWLockImpl::RemoveWriter()
- {
- switch (WaitForSingleObject(m_mutex, INFINITE))
- {
- case WAIT_OBJECT_0:
- if (--m_writersWaiting == 0 && m_writers == 0)
- SetEvent(m_readEvent);
- ReleaseMutex(m_mutex);
- break;
- default:
- cout<<"cannot lock reader/writer lock"<<endl;
- }
- }
- void CRWLockImpl::ReadLockImpl()
- {
- HANDLE h[2];
- h[0] = m_mutex;
- h[1] = m_readEvent;
- switch (WaitForMultipleObjects(2, h, TRUE, INFINITE))
- {
- case WAIT_OBJECT_0:
- case WAIT_OBJECT_0 + 1:
- ++m_readers;
- ResetEvent(m_writeEvent);
- ReleaseMutex(m_mutex);
- assert(m_writers == 0);
- break;
- default:
- cout<<"cannot lock reader/writer lock"<<endl;
- }
- }
- bool CRWLockImpl::TryReadLockImpl()
- {
- for (;;)
- {
- if (m_writers != 0 || m_writersWaiting != 0)
- return false;
- DWORD result = TryReadLockOnce();
- switch (result)
- {
- case WAIT_OBJECT_0:
- case WAIT_OBJECT_0 + 1:
- return true;
- case WAIT_TIMEOUT:
- continue;
- default:
- cout<<"cannot lock reader/writer lock"<<endl;
- }
- }
- }
- void CRWLockImpl::WriteLockImpl()
- {
- AddWriter();
- HANDLE h[2];
- h[0] = m_mutex;
- h[1] = m_writeEvent;
- switch (WaitForMultipleObjects(2, h, TRUE, INFINITE))
- {
- case WAIT_OBJECT_0:
- case WAIT_OBJECT_0 + 1:
- --m_writersWaiting;
- ++m_readers;
- ++m_writers;
- ResetEvent(m_readEvent);
- ResetEvent(m_writeEvent);
- ReleaseMutex(m_mutex);
- assert(m_writers == 1);
- break;
- default:
- RemoveWriter();
- cout<<"cannot lock reader/writer lock"<<endl;
- }
- }
- bool CRWLockImpl::TryWriteLockImpl()
- {
- AddWriter();
- HANDLE h[2];
- h[0] = m_mutex;
- h[1] = m_writeEvent;
- switch (WaitForMultipleObjects(2, h, TRUE, 1))
- {
- case WAIT_OBJECT_0:
- case WAIT_OBJECT_0 + 1:
- --m_writersWaiting;
- ++m_readers;
- ++m_writers;
- ResetEvent(m_readEvent);
- ResetEvent(m_writeEvent);
- ReleaseMutex(m_mutex);
- assert(m_writers == 1);
- return true;
- case WAIT_TIMEOUT:
- RemoveWriter();
- default:
- RemoveWriter();
- cout<<"cannot lock reader/writer lock"<<endl;
- }
- return false;
- }
- void CRWLockImpl::UnlockImpl()
- {
- switch (WaitForSingleObject(m_mutex, INFINITE))
- {
- case WAIT_OBJECT_0:
- m_writers = 0;
- if (m_writersWaiting == 0) SetEvent(m_readEvent);
- if (--m_readers == 0) SetEvent(m_writeEvent);
- ReleaseMutex(m_mutex);
- break;
- default:
- cout<<"cannot unlock reader/writer lock"<<endl;
- }
- }
- DWORD CRWLockImpl::TryReadLockOnce()
- {
- HANDLE h[2];
- h[0] = m_mutex;
- h[1] = m_readEvent;
- DWORD result = WaitForMultipleObjects(2, h, TRUE, 1);
- switch (result)
- {
- case WAIT_OBJECT_0:
- case WAIT_OBJECT_0 + 1:
- ++m_readers;
- ResetEvent(m_writeEvent);
- ReleaseMutex(m_mutex);
- assert(m_writers == 0);
- return result;
- case WAIT_TIMEOUT:
- default:
- cout<<"cannot lock reader/writer lock"<<endl;
- }
- return result;
- }
- // MyRWLockWin32.cpp : 定义控制台应用程序的入口点。
- //
- #include "RWLockImpl.h"
- //创建一个读写锁对象
- CMyRWLock g_myRWLock;
- volatile int g_counter = 0;
- //线程函数
- unsigned int __stdcall StartThread(void *pParam)
- {
- int lastCount = 0;
- for (int i = 0; i < 10000; ++i)
- {
- g_myRWLock.ReadLock();
- lastCount = g_counter;
- //在读锁域,两个线程不断循环交替访问全局变量g_counter
- for (int k = 0; k < 100; ++k)
- {
- if (g_counter != lastCount)
- cout<<"the value of g_counter has been updated."<<endl;
- Sleep(0);
- }
- g_myRWLock.Unlock();
- g_myRWLock.WriteLock();
- //在写锁域,只有一个线程可以修改全局变量g_counter的值
- for (int k = 0; k < 100; ++k)
- {
- --g_counter;
- Sleep(0);
- }
- for (int k = 0; k < 100; ++k)
- {
- ++g_counter;
- Sleep(0);
- }
- ++g_counter;
- if (g_counter <= lastCount)
- cout<<"the value of g_counter is error."<<endl;
- g_myRWLock.Unlock();
- }
- return (unsigned int)0;
- }
- int main(int argc, char* argv[])
- {
- HANDLE hThread1, hThread2;
- unsigned int uiThreadId1, uiThreadId2;
- //创建两个工作线程
- hThread1 = (HANDLE)_beginthreadex(NULL, 0, &StartThread, (void *)NULL, 0, &uiThreadId1);
- hThread2 = (HANDLE)_beginthreadex(NULL, 0, &StartThread, (void *)NULL, 0, &uiThreadId2);
- //等待线程结束
- DWORD dwRet = WaitForSingleObject(hThread1,INFINITE);
- if ( dwRet == WAIT_TIMEOUT )
- {
- TerminateThread(hThread1,0);
- }
- dwRet = WaitForSingleObject(hThread2,INFINITE);
- if ( dwRet == WAIT_TIMEOUT )
- {
- TerminateThread(hThread2,0);
- }
- //关闭线程句柄,释放资源
- CloseHandle(hThread1);
- CloseHandle(hThread2);
- assert (g_counter == 20000);
- system("pause");
- return 0;
- }