Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iPhone multi-threaded AddressBook manipulation

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

like image 690
Marco Avatar asked Mar 04 '10 20:03

Marco


1 Answers

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.

like image 149
Kiril Avatar answered Oct 04 '22 18:10

Kiril