[问题] 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