iPhone multi-threaded AddressBook manipulation - iphone

I have been using the AddressBook api of the iPhone for some time now. But doing some refactoring to improve application performance I have decided to "reuse" the ABAddressBookRef returned by AddressBookCreate because I noticed there are large performance improvements doing that. However, I am getting EXEC_BAD_ACCESS errors now randomly, and I think the reason is in this "caveat" in the iPhone reference implementation: http://developer.apple.com/iphone/library/documentation/ContactData/Conceptual/AddressBookProgrammingGuideforiPhone/300-BasicObjects/BasicObjects.html#//apple_ref/doc/uid/TP40007744-CH3-SW1
Important: Instances of ABAddressBookRef cannot be used by multiple threads. Each thread must make its own instance by calling ABAddressBookCreate.
Now, I thought that simply meant it was not thread-safe so I had to synchronise access to the API, but maybe I am wrong, and there is some other reasons multiple threads mess up the data structure?
Can someone confirm if it is indeed a thread-safe issue (so #synchronize should work) or some other issue?
Cheers

This is not a thread safety issue... there is no way for you to solve it with locks. The comment makes it pretty clear:
Important: Instances of ABAddressBookRef cannot be used by
multiple threads. Each thread must
make its own instance by calling
ABAddressBookCreate.
What you can do is create a single instance of the ABAddressBook and create a producer/consumer architecture that would manage the access to the object.
The wrapper will have a main thread which does one thing only: reads operation requests from a blocking queue, then performs the operations on the address book. All your threads will queue their operations to the single queue and the wrapper will execute those actions; if there is nothing in the queue then the wrapper will block until there is something in the queue.
This should solve the problem of not being allowed to use the ABAddressBookRef from multiple threads.

Related

Running C code in an Objective C (Cocoa) Thread (for iOS)

First of all, I am a a very new Objective C/Cocoa iOS Developer but I've written C/C++ applications before.
So I managed to run the Rabbitmq-c (http://hg.rabbitmq.com/rabbitmq-c/) client inside my iPhone App, and I can connect to Rabbitmq directly from my app and even consume a queue item. So all's good.
Now my problem is, my iPhone app needs to use the rabbitmq-c library to poll for incoming messages in from the server. Probably there will be, an almost infinite while loop.
Do I have to take this to a new thread? Ideally, I want to wrap the rabbitmq-c class as an Async objective C class and use NSNotification (or something similar) to notify my UI. I'm a bit leery of creating a new thread, as I read about stuffs like Runloop etc can solve a lot of problems without using an extra thread.
What is the best way for me to go about this? Any examples of code or directions would be helpful. Please remember, I am not dealing with an Objective C code/Coca rabbitmq library here, I'm using C code inside my iPhone app.
Thanks
Subrat
don't block the main thread with your server polling.
since the operation never ends, create your own thread and run loop for this server polling. you can potentially use the run loop (each thread has one) instead of the infinite while. the alternatives involve regularly spawning threads. it's easiest to just use one thread for this.
once you have an update, post the notification (if you choose NSNotification) from the main thread -- UIKit is meant to operate from the main thread only.
for samples, i'd begin with samples related to NSRunLoop and CFRunLoop.
good luck
You can also create custom delegates for updating the UI, or the stuff related to UIKit.
Notifications might be a little easier to code and offer the advantage that multiple objects can observe one notification. With delegates, such a thing cannot be done without modifying the delegating object (and is unusual).
Some advantages of delegating:
The connection between delegating object and delegate is made clearer, especially if implementing the delegate is mandatory.
If more than one type of message has to be passed from delegatee to delegate, delegating can make this clearer by specifying one delegate method per message.
Or other way is to write method to receive messages. This method can have infinite loop.
Later you can put this method in background thread like this.
[self performSelectorInBackground:#selector(receiveMessages) withObject:nil];

What is meant by CoreData is not thread safe?

In Obj-C, what does it mean in simple terms;
"CoreData is not thread safe"
OR in general what is "not thread safe" ?
#d11wtq's answer is correct only when writing your own code or designing your own APIs.
It is entirely incorrect when working with a set of APIs and quite specifically wrong when working with Core Data.
In the context of working with Mac OS X and iOS, thread safety must always be considered in the context of working with the system APIs. Even using, say, an NSArray means that you are working with the system APIs.
OR in general what is "not thread
safe" ?
A non-thread safe API is an API where you cannot interact with the API from multiple threads simultaneously. There may also be additional restrictions that most often involve the main thread. For example, almost all drawing operations must occur on the main thread on both Mac OS X and iOS.
The Apple documentation assumes thread safety is the exceptional case. That is, an API is only thread safe if the documentation explicitly claims thread safety. If there is no mention of thread safety, you must assume that the API is not thread safe.
In Obj-C, what does it mean in simple
terms; "CoreData is not thread safe"
That statement is not quite correct, but it is a safe assumption.
In Core Data's case, the thread interaction behavior is extremely well documented.
In short, parts of the API are thread safe (the store coordinator, for example) and parts are quite explicitly not thread safe. While the MOC provides lock and unlock methods, you can also use external locking. But don't. It will be less efficient and more fragile; significantly so. In general, don't use the internal locking either. CoreData is optimized around having a context per thread/queue.
(Answer fixed based on TC's feedback. Thanks.)
UPDATE | Please see #bbum's answer. I accept that my answer is flawed and #bbum is correct.
If something is described as "not thread safe", it means that no special precautions have been taken to ensure it won't crash should two separate threads try to use it simultaneously. In general, code that is to be used by more than one thread requires explicit locks (or #synchronize blocks) wrapping around aspects of the code. In particular, any object/variable that will be modified would almost certainly cause a crash if two threads happened to write to it at the same time (since they'd be writing to the same memory address). Similarly, if one thread was reading a variable while another was writing to it, garbage would be returned and the program would likely crash.
Using #synchronized, or NSLock or a POSIX mutex etc, ensures that only one thread can execute a particular block of code at any given time. The other threads get blocked and have to wait until the lock is released. There is a slight performance hit with using locks (and of course some development overhead having to think about them), so often code expressly declares that it is not thread safe, leaving you, the adopter of the code, to place locks as needed yourself (or limit execution of the non thread-safe to a single thread).
See the Apple documentation for more information about threading and thread safety:
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjectiveC/Articles/ocThreading.html#//apple_ref/doc/uid/TP30001163-CH19-BCIIGGHG

What happens when 2 threads write to same object?

Hi there
i am wondering what happens, if 2 threads writes to an object at the same time?
Not sure if this should be threads, i have multiple copies of a view, each copy access and writes to a nsuserdefault object.
What happens if two or more copies of the view writes to the same object? is there some kind of locking mechanism?
Thanks
The NSUserDefaults class is thread-safe, see the documentation. So yes, there is probably some kind of locking mechanism inside.
If 2 threads write to the same object or structure without some kind of locking primitive, then very bad things will happen. At best, you'll end up with inconsistent state. At worst, your app will crash. NSUserDefaults is defined to be thread safe, so -- yes -- it is using locking of some kind.
If you have views running in different threads all writing to the same object, that is indicative of a whole different problem. The UIKit isn't completely thread safe. Most UI interaction must be done from the main thread.
The docs have a bunch of information on this.

Will the system send an NSWillBecomeMultiThreadedNotification when I create POSIX threads?

I tried it, but I think this notification isn't coming. Is that the normal case?
No, this notification is sent by NSThread. If you're using ordinary pthreads, it won't be sent.
From the docs:
Protecting the Cocoa Frameworks For
multithreaded applications, Cocoa
frameworks use locks and other forms
of internal synchronization to ensure
they behave correctly. To prevent
these locks from degrading performance
in the single-threaded case, however,
Cocoa does not create them until the
application spawns its first new
thread using the NSThread class. If
you spawn threads using only POSIX
thread routines, Cocoa does not
receive the notifications it needs to
know that your application is now
multithreaded. When that happens,
operations involving the Cocoa
frameworks may destabilize or crash
your application.
To let Cocoa know that you intend to
use multiple threads, all you have to
do is spawn a single thread using the
NSThread class and let that thread
immediately exit. Your thread entry
point need not do anything. Just the
act of spawning a thread using
NSThread is enough to ensure that the
locks needed by the Cocoa frameworks
are put in place.
If you are not sure if Cocoa thinks
your application is multithreaded or
not, you can use the isMultiThreaded
method of NSThread to check.
It should also be noted that 'times have changed' since NSWillBecomeMultiThreadedNotification was added to Foundation. Multi-threaded programming is now much, much more common. It's now entirely within the realm of possibility, even likely, that you'll never see this notification posted in an app. Modern apps become multi-threaded very early in their life, possibly before any part of your code is ever executed. Also from the documentation:
If you are developing a Cocoa library,
you can register as an observer for
the
NSWillBecomeMultiThreadedNotification
if you want to be notified when the
application becomes multithreaded. You
should not rely on receiving this
notification, though, as it might be
dispatched before your library code is
ever called.
I'd use [NSThread isMultiThreaded] instead of relying on NSWillBecomeMultiThreadedNotification.

Running a socket stream in a thread

I have an application that opens a connection with 2 sockets (in and out) and I want to have them working in a thread.
The reason that I want them to be in a separate thread is that I don't want my application to freeze when I receive data, and this can happen anytime as long as the application is running.
Currently I have a class that handle also network communication and I run this class in an NSOperation, I'm not sure if it's the best solution.
I'm not very familiar with threading so guys if you could give me some help I would be very grateful.
Thanks
First, you should know that you can use the same socket to send and receive data — they're generally bi-directional. You should be able to share a reference to the same socket among multiple threads of execution.
Second, unless you'll be receiving large amounts of data and have experienced performance issues with your UI, I would delay optimizing for it. (Don't get me wrong, this is a good consideration, but premature optimization is the root of all evil, and simpler is generally better if it performs adequately.)
Third, NSOperation objects are "single-shot", meaning that once the main method completes, the operation task cannot be used again. This may or may not be conducive to your networking model. You might also look at NSThread. The fact that you already have the functionality "factored out" bodes well for your design, whatever turns out to be best.
Lastly, threading is a complex topic, but a good place to start (especially for Objective-C) is Apple's Threading Programming Guide.