Since your objects are local threads, why do you need to block to protect them at all? Each thread that getsInstance () calls does not depend on any other thread, so why not just check if a singleton exists and create one if necessary? Blocking will be needed only if several threads tried to access the same singleton, which is impossible in your design, since it is higher.
EDIT: Turning to two other questions ... I see no reason why using TlsAlloc / TlsGetValue, etc. will not work as you expected. Since the memory containing the pointer to your singleton is available only for the corresponding thread, there will be no problems with lazy initialization. However, there is no explicit callback interface to clear them.
An obvious solution for this would be to have a method that is called by all of your main stream functions, which clears the created singleton, if any.
If it is very likely that the thread will create a singleton, a simpler template might be to create a singleton at the beginning of the main function of the stream and delete it at the end. You can then use RAII either by creating a singleton on the stack, or by holding it in std :: auto_ptr <> so that it is deleted when the stream ends. (If the flow does not end abnormally, but if it does, all bets will be disconnected and the leaked object will be the least of your problems.) Then you can simply transfer the singleton or save it in TLS or save it in a class member, if most of the functionality flow is in the same class.
source share