简体   繁体   English

如何在c ++中同步getter和setter方法

[英]how to synchronize getter and setter method in c++

If 2 following methods in same class. 如果同一类中有以下两种方法。

  bool CSettings::GetDelayTimer()
  {     
     return m_iTimerDelay;     
  }

  void CSettings::SetDelayTimer(int iTimerdelay)
  {
    m_iTimerDelay = iTimerdelay;
  }

In order to synchronize above methods I created following lock/unlock methods. 为了同步上面的方法,我创建了以下锁定/解锁方法。

  void CSettings::Lock()
  {
    DWORD dwRet = WaitForSingleObject(m_hSettingsLock, INFINITE);
    if( dwRet == WAIT_OBJECT_0)
      return;
  }

  void CSettings::UnLock()
  {
    ReleaseMutex(m_hSettingsLock);
  }

how do I synchronize these getter/setter methods using lock/unlock. 如何使用锁定/解锁同步这些getter / setter方法。 If I use lock in getter method I don't get chance to unlock as it will return before unlocking. 如果我在getter方法中使用lock,我将无法解锁,因为它会在解锁之前返回。 I mean to say : Lock(); 我的意思是说:Lock(); return m_iTimerDelay; return m_iTimerDelay; UnLock(); 开锁(); Is it gonna work? 它会起作用吗? Applying Lock/UnLock to setter is not a problem. 将Lock / UnLock应用于setter不是问题。

Any Idea to synchronize these methods? 任何同步这些方法的想法?

Regards, Khurram. 此致,Khurram。

Use RAII . 使用RAII Make an object whose constructor acquires the lock and whose destructor releases it. 创建一个对象,其构造函数获取锁并且其析构函数释放它。 Then you can just do: 然后你可以这样做:

{
    ScopedLock f(m_hSettingsLock);
    return m_iTimerDelay;
}

Let ScopedLock::~ScopedLock release the lock. ScopedLock::~ScopedLock释放锁。

Alternatively, the most likely inferior: 或者,最可能的劣势:

{
    Lock();
    bool ret = m_iTimerDelay;
    Unlock();
    return ret;
}

Note that in both cases the returned value can be stale. 请注意,在这两种情况下,返回的值都可能是陈旧的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM