[問題] create singleInstance at same time

作者: 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還未初始化所以不能用
作者: loveme00835 (髮箍)   2019-04-06 13:58:00
你有 foo 不用還去創新的幹嘛?
作者: kingofsdtw (不能閒下來!!)   2019-04-06 15:12:00
他是強調同一時間,去get還未初始化的SingleInstance
作者: lovejomi (JOMI)   2019-04-06 15:15:00
magic static
作者: loveme00835 (髮箍)   2019-04-06 15:51:00
看來你還是沒懂 foo->getInstance() 這個呼叫奇怪的地方
作者: aiwhat   2019-04-06 16:51:00
::
作者: idiont (supertroller)   2019-04-06 17:04:00
mutex
作者: sarafciel (Cattuz)   2019-04-06 17:14:00
起thread前先叫一次就好啦XD
作者: loveme00835 (髮箍)   2019-04-06 18:18:00
這只是把初始化的時機拉到跑執行緒以前而已,這跟你另外呼叫一個函式初始化意義差不多
作者: sarafciel (Cattuz)   2019-04-06 22:51:00
mutex那個應該就是面試官想看的答案了至於mutex 你能在static memeber function call到就代表他也是static的 所以進entry point前就會建好了
作者: layan (教練我想打球 T_T)   2019-04-07 19:19:00
http://www.modernescpp.com/index.php/component/jaggyblog/thread-safe-initialization-of-a-singleton#comment-651
作者: kingofsdtw (不能閒下來!!)   2019-04-07 19:34:00
作者: Killercat (殺人貓™)   2019-04-10 20:24:00
為了一個可以迂迴解決的問題 讓每次getInstance都要額外開個鎖 老實講這種理論狂戰士要是跟他共事你要小心不過Meyers Singleton的確很讚
作者: tinlans ( )   2019-04-12 19:14:00
為什麼有 std::call_once() 可以用卻把它晾在一邊?

Links booklink

Contact Us: admin [ a t ] ucptt.com