views:

136

answers:

2

I'm working on an iphone app but this is probably a general question.

I have a singleton Model class and there would be scenarios where multiple NSOperations (threads) would exist and work with the singleton object. If they all call the same method in this object, do i need to have some locking mechanism?

Or can this method be executed only one at a time?

I do not have a computer science background but my guess is that all threads would have their CALL to the same address (this method). Also can you please suggest a good beginner programming book that discusses general programming concepts. I don't have the brains for Knuth kinda books.

A: 

Having a singleton does not solve the problems of access from multiple threads.

Depending on the nature of your data and how it's updated, you may likely need to protect it with some sort of locking mechanism.

Claus Broch
+1  A: 

Basically you only need to worry about synchronisation if data is MODIFIED (even if only one "thread" modifies it and the rest only read it). If one or more threads do modify the data in the singleton (or any data the singleton refers to), then you need some sort of algorithm to deal with the data contention (beginers should stick to "lock" based algorthims). This is true of all data shared by multiple threads, not just singletons.

Functions have nothing to do with the problem (though functions will often change data and the same function will change the same data and read the same when called on multiple threads). If the function is a 'const' function (i.e. can't/won't modify any data, then it is safe to call on multiple threads, so long as nothing else touches the data that function reads).

Grant Peters