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 22:33:01 -0600
On Wednesday, July 11, 2001, at 09:33 PM, Rob Rix wrote:
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.
Well, only the singleton instance will be able to change its data, but
others will access it for reading (it checks the state of some of the
file system).
So, will I need locks when reading from it, or just writing?
That's a question you have to answer. The typical example problem is the
case of two threads needing to increment x. Like
x = x + 1;
typically this turns into
load x into register
add 1 to register
write register to x
since you can preempt on any of those three instructions, you need to
put a lock around it to make the whole thing atomic at the asm
instruction level. Think about how it would work if you interrupted into
another thread doing the exact same thing between lines 2 and 3.
So, you've got to figure out if two threads can do anything which
changes state on the object. If so, then you'll need to protect them. If
that's not the case, you'll need to ask yourself if it's OK for a reader
thread to be able to interrupt the writer thread and look at potentially
inconsistent data. If that can't happen, then I'd also protect it with
locks.
Threaded programming is an order of magnitude (at least!) harder than
single threaded programming. And Preemptive is so much harder than
co-operative (like we did with Mac OS 9). If you haven't done it, I'd
suggest getting a book outlining it. Something on operating systems or
the pthreads book from O'Reilly would be someplace to start. Otherwise,
you'll have a hard time with things like race conditions, deadlocks, etc.
Mike