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:22:17 -0600
On Wednesday, July 11, 2001, at 01:01 PM, Axel 'Mikesch' Katerbau wrote:
Hi Rob,
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
}
As for messaging the object. It's not a problem in and of itself. There
will be the usual issues of making sure the object properly obtains
locks for access to data which two competing threads are trying to
access, but these are all basic threading issues. Just make sure your
object(s) follow the rules for being used in a multi-threaded
environment, and you'll be fine.
Mike