On 28/01/2010, at 3:37 AM, Scott Ribe wrote:

> Of course this code does not necessarily *prevent* you from making multiple
> Debug instances, but neither does the code Graham posted if you try to call
> [Debug sharedDebug] from multiple threads.


Calling a singleton method from multiple threads does not make multiple 
instances. It returns the same shared instance regardless (the 'static' keyword 
does not create thread local storage*). In fact that might be cause for concern 
if you are using it from multiple threads - you need to design the class itself 
to be thread-safe.

If you do want multiple instances, a simple alloc/init when needed is all you 
need to do, but if you truly want to enforce a single instance under all 
possible conditions, you'd need to override -init and -copyWithZone: and 
probably others to always return the singleton.

*GCC supports thread-local storage using the __thread keyword. Use that instead 
of 'static' and you will get a separate instance per thread, though as a GCC 
feature not a language feature the code is less portable.

--Graham


_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Reply via email to