作者:
kingofsdtw (ä¸èƒ½é–’下來!!)
2019-04-06 12:44:25開發平台(Platform): (Ex: Win10, Linux, ...)
gun c
編譯器(Ex: GCC, clang, VC++...)+目標環境(跟開發平台不同的話需列出)
額外使用到的函數庫(Library Used): (Ex: OpenGL, ...)
問題(Question):
HPe 面試題
有個class 叫foo是 single instance
Instance為NULL
如果有兩個thread "同時" Get singleInstance 該怎解決這問題?
餵入的資料(Input):
同一時間init foo class
thread1: pfool = foo::getInstance();
thread2: pfool = foo::getInstance();
class foo{
public:
static foo *getInstance(){
if( instance == null )
instance = new foo();
return instance;
}
private:
foo(){
}
static foo* instance;
std::mutex mutex;
}
預期的正確結果(Expected Output):
只會有一個pf位址
錯誤結果(Wrong Output):
程式碼(Code):(請善用置底文網頁, 記得排版,禁止使用圖檔)
補充說明(Supplement):
我記得曾經看過一篇文章getInstance mutex還未初始化所以不能用