• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
Re: Singleton instances and multithreading
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

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


References: 
 >Re: Singleton instances and multithreading (From: Rob Rix <email@hidden>)

  • Prev by Date: Annoying Java Class/Nib problem
  • Next by Date: Re: Singleton instances and multithreading
  • Previous by thread: Re: Singleton instances and multithreading
  • Next by thread: Re: Singleton instances and multithreading
  • Index(es):
    • Date
    • Thread