Implement synchronous locks in C + +, similar to synchronize (object) {.... }

Source: Internet
Author: User

In the project to do C + + found, because used to C # lock () {} and Java Synchronize () {},windows with the critical zone, mutual exclusion, kernel events, signal volume used up not too accustomed, so intend to own in VC + + packaging a similar stuff. Encapsulation of this I decided to use a critical section to do, the final form is as follows:

synchronize(object)

{

 //....无论此处是否发生异常,object都能被释放掉。和c#的lock一样。

}

Don't say much, start code. Define a mutex class first

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

Implemented as follows

Mutex.cpp file

#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);

}

In writing a lock class to wrap

Header File File

//为了方便把头文件定义到了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;
};

Implementation of the Lock class: Lock.cpp file

#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;


}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.