c++ 锁

class Mutex
{
public:
    Mutex(void);
    ~Mutex(void);
    void Lock();
    void UnLock();
private:
    CRITICAL_SECTION m_criticalSection;
};


#include "Mutex.h"

Mutex::Mutex(void)
{
    InitializeCriticalSection(&m_criticalSection);
}

Mutex::~Mutex(void)
{
    DeleteCriticalSection(&m_criticalSection);//保证对象被析构时候能够删除临界区
}

void Mutex::Lock()
{
     EnterCriticalSection(&m_criticalSection);
}

void Mutex::UnLock()
{
    LeaveCriticalSection(&m_criticalSection);

}


//------------------------------------------------------------------------------------------------

在写一个Lock类来包装

头文件文件



//为了方便把头文件定义到了Mutex.h文件里面去了,修改Mutex.h如、//下:
#define synchronized(M)  for(Lock M##_lock = M; M##_lock; M##_lock.SetUnlock())//这句话后面会用到

class Mutex
{
public:
    Mutex(void);
    ~Mutex(void);
    void Lock();
    void UnLock();
private:
    CRITICAL_SECTION m_criticalSection;
};

class Lock
{
public:
    Lock(Mutex &mutex);
    ~Lock(void);
    void SetUnlock();
    operator bool () const;
private:
    Mutex &m_mutex;
    bool m_locked;
};

Lock类的实现:Lock.cpp文件

#include "Mutex.h"

Lock::Lock(Mutex &mutex): m_mutex(mutex), m_locked(true)
{
    m_mutex.Lock();
}

Lock::~Lock(void)
{/*一定要在析构函数中解锁,因为不管发生什么,只要对象离开他的生命周期(即离开大括号),都会调用其析构函数*/
     m_mutex.UnLock();
}

void Lock::SetUnlock()
{
     m_locked = false;
}

Lock::operator bool() const
{
    return m_locked;


}

到这里算是基板上告一段落了,你可以这么用。

Mutex _mutex;

{

Lock lock(_mutex);

//...在这里同步

}

但还差一点点,我要的目标是synchronize(){.....}

简单!!!注意Mutex.h文件里面的宏,没错!就他了!!! 

#define synchronized(M)  for(Lock M##_lock = M; M##_lock; M##_lock.SetUnlock())

大功告成!!!

来测试下

实际测试



#include "Mutex.h"

Mutex mutex1;//我的互斥量
into thread_count = 0;
DWORD CALLBACK thread_proc(LPVOID params)
{
    for(int i = 0; i < 10; ++i)
    {
            synchronized(mutex1)//这里同步!
            {
                for(char c = 'A'; c <= 'Z'; ++c)
                {
                    printf("%c",c);
                    Sleep(2);
                }
                printf("\n");
            }
    }
    thread_count--;
    return 0;
}

int _tmain(int argc, _TCHAR* argv[])
{
    thread_count = 4;
    CreateThread(0, 0, thread_proc, 0, 0, 0);
    CreateThread(0, 0, thread_proc, 0, 0, 0);
    CreateThread(0, 0, thread_proc, 0, 0, 0);
    CreateThread(0, 0, thread_proc, 0, 0, 0);
    while (thread_count) 
        Sleep(0);
    getchar();
    DeleteCriticalSection(&g_cs);
    return 0;


}

ABCD...........Z

ABCD............Z

ABCD...........Z

ABCD............Z

ABCD...........Z

ABCD............Z

......................

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值