Question about "singleton in multi-thread"
-
Hello, everyone! I encounter a strange question. I defined a singleton class like this: static CMySocket& GetMySocket(); CMySocket& CMySocket::GetMySocket() { static CMySocket temp; return temp; } In single thread, it works properly, but in Multi-thread, (I can ensure in main thread, invoke CMySocket::GetMySocket first), when invoke GetMySocket I get different instance , who can tell me , why? Thanks a lot and best regards.
-
Hello, everyone! I encounter a strange question. I defined a singleton class like this: static CMySocket& GetMySocket(); CMySocket& CMySocket::GetMySocket() { static CMySocket temp; return temp; } In single thread, it works properly, but in Multi-thread, (I can ensure in main thread, invoke CMySocket::GetMySocket first), when invoke GetMySocket I get different instance , who can tell me , why? Thanks a lot and best regards.
As i recall u need to declare a certain macro for a singleton class both when using it in a single threaded and apartment. try to look in the MSDN for DECLARE_CLASSFACTORY_SINGLETON macro. hope this helps you Yaron Ask not what your application can do for you, Ask what you can do for your application
-
As i recall u need to declare a certain macro for a singleton class both when using it in a single threaded and apartment. try to look in the MSDN for DECLARE_CLASSFACTORY_SINGLETON macro. hope this helps you Yaron Ask not what your application can do for you, Ask what you can do for your application
-
YaronNir wrote:
try to look in the MSDN for DECLARE_CLASSFACTORY_SINGLETON macro.
that use to make COM Class SingleTon!
right! if he isn't using COM, i suggest he use a protection (critical section) because if in multithreaded application both threads recquire an instance to the class, one should acquire a real one while the other acquire a false one..... hope this helps Ask not what your application can do for you, Ask what you can do for your application