10 Haziran 2019 Pazartesi

Double Checked Locking

Örnek
İskelet kod olarak şuna benzer
Singleton* Singleton::instance () {
   Singleton* tmp = pInstance;
   ... // insert memory barrier (1)
   if (tmp == 0) {
      Lock lock;
      tmp = pInstance;
      if (tmp == 0) {
         tmp = new Singleton;
         ... // insert memory barrier (2)
         pInstance = tmp;
      }
   }
   return tmp;
}
Örnek
Şuna benzer. volatile gerekli mi bilmiyorum
volatile T* pInst = 0;
T* GetInstance()
{
  if (pInst == NULL) // unsafe check to avoid unnecessary and maybe slow lock()
  {
   lock(); // after this, only one thread can access pInst
   if (pInst == NULL) // check again because other thread may have modified it
     pInst = new T;
   unlock();
  }
  return pInst;
}

Hiç yorum yok:

Yorum Gönder