我有以下代碼:正確刪除單
MyClass.h:
static MyMutex instanceMutex;
static MyClass* getInstance();
static void deleteInstance();
MyClass.c:
MyMutex MyClass::instanceMutex;
MyClass* MyClass::getInstance()
{
if (theInstance == 0)
{
instanceMutex.acquire();
if (theInstance == 0)
{
theInstance = new MyClass();
}
instanceMutex.release();
}
return theInstance;
}
void MyClass::deleteInstance()
{
if (theInstance != 0)
{
instanceMutex.acquire();
if (theInstance != 0)
{
theInstance->finalize();
delete theInstance;
theInstance = 0;
}
instanceMutex.release();
}
return;
}
我對此有2個問題:
- 上述代碼是否正確且安全?
後我稱之爲 '刪除theInstance' MyClass中:: deleteInstance(),我然後調用
- theInstance = 0;
- instanceMutex.release();
但是,如果實例被刪除,那怎麼可能呢?這不是班級的記憶嗎?
雙檢鎖和一個單身一下子!天啊。 –
你打算在多線程環境中使用這個單例嗎?如果不是,爲什麼鎖定?如果是,爲什麼刪除單身人士的方法?順便說一句,爲什麼在程序執行期間需要刪除單身人士? – ArturFH
finalize()取消線程 – Kam