致开

Concurrency Programming - Write your own ReaderLock and WriterLock

This article is based on the previous articles, since we'll use the mutex and semaphore in our class. This artical will mainly be consisted by the C++ code, not too many words.

#include <windows.h>

class Lock
{
public:
    Lock()
    {
        hMutex 
= CreateMutex(NULL, false"OWNLOCK");
        hSemaphore 
= CreateSemaphore(NULL, 11"OWNSEMAPHORE");
        iReaderCount 
= 0;
    }

    
void AcquireReadLock()
    {
        WaitForSingleObject(hMutex, INFINITE);

        
if(++iReaderCount == 1)
            WaitForSingleObject(hSemaphore, INFINITE);
        ReleaseMutex(hMutex);
    }

    
void ReleaseReadLock()
    {
        WaitForSingleObject(hMutex, INFINITE);
        
if(--iReaderCount == 0)
            ReleaseSemaphore(hSemaphore, 
1, NULL);
        ReleaseMutex(hMutex);
    }

    
void AcquireWriteLock()
    {
        WaitForSingleObject(hSemaphore, INFINITE);
    }

    
void ReleaseWriteLock()
    {
        ReleaseSemaphore(hSemaphore, 
1, NULL);
    }
    
private:
    HANDLE hMutex;
    HANDLE hSemophore;
    
int iReaderCount;
};

Regarding when to use the lock, I'm saying that if the data is shared between threads, any access to this piece of data should be protected, locked. Also using the right type of lock is also necessary, otherwise it will be the bottleneck of your application.

Another issue is that at which granularity to add the lock. My suggestion is that don't add too many locks at one time, which will cause hard to locate the problems if it happens. You should at as few locks as possiable at one time.

posted on 2008-12-30 21:34 Xiaxi 阅读(224) 评论(0)  编辑 收藏 引用


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   博问   Chat2DB   管理


<2008年12月>
30123456
78910111213
14151617181920
21222324252627
28293031123
45678910

导航

统计

常用链接

留言簿(1)

随笔档案

文章分类

文章档案

搜索

最新评论

阅读排行榜

评论排行榜