Re: Singleton instances and multithreading
Re: Singleton instances and multithreading
- Subject: Re: Singleton instances and multithreading
- From: Mike Shields <email@hidden>
- Date: Wed, 11 Jul 2001 16:08:13 -0600
Specifically, I want to call the +sharedInstance method on a class I've
developed for an application. Can I do that and then safely message the
returned object without using DO?
In general, no. Typically the singleton class method first checks if
the singleton is already instantiated before instantiating the
singleton if needed. If the check is not known to be thread safe then
you can run in trouble with more than one singleton instance (which is
a bad thing by definition :-) )
Well if you've written it yourself, you can make it threadsafe by virtue
of using NSLocks. So there's no reason a singleton method couldn't be
threadsafe, but you've got to think about it in advance. I think you
could put some stuff in there to check the multithreaded-ness of the
program and skip the locking if it's single threaded.
+sharedInstance
{
[mylock lock];
do stuff to check/create singleton
[mylock unlock];
return singleton instance
}