exception - Singleton constructor fails c++ - what can be? -
i facing huge problem: have singleton class. program multi-threaded mfc, singleton's constructor can called different threads. surrounded singleton instance-getter function mutex avoid deadlocks , multiple constructions. call of below meant function fails directly @ first time.
the function looks (log_msg macro logs given string log file):
myclass& myclass::singleton () { log_msg("myclass::singleton -> jump in"); static cmutex oinitmutex; try { csinglelock osinglelock((csyncobject *) &oinitmutex, true); log_msg("!!! singleton lock okay !!!"); static myclass omyclassinstance; log_msg("!!! singleton construction okay !!!"); return omyclassinstance; } catch(...) { cstring excmsg("unexpected exception creating myclass singleton instance!"); log_msg(excmsg); throw excmsg; } }
i've figured out, construction of singleton object not fail (since "!!! singleton construction okay !!!" message).
log output says:
09.04.2013 ;07:14:51:832;"myclass::singleton -> jump in" 09.04.2013 ;07:14:51:841;"!!! singleton lock okay !!!" ... (constructor logs => nothing unexpected in it!!! runs fine, must!!!) 09.04.2013 ;07:14:52:125;"!!! singleton construction okay !!!" 09.04.2013 ;07:14:52:170;"unexpected exception creating myclass singleton instance!"
what means? when return statement throw exception(s)??? please me resolve matter...
while doesn't answer particular question, it's still solution overall problem: don't need mutex at all. c++11 standard [stmt.dcl]§4 specifies (when talking static
variables local functions):
if control enters declaration concurrently while variable being initialized, concurrent execution shall wait completion of initialization.88 if control re-enters declaration recursively while variable being initialized, behavior undefined.
where note 88 is:
note 88: implementation must not introduce deadlock around execution of initializer.
in other words, compiler introduces synchronisation you; no need manually.
Comments
Post a Comment