views:

182

answers:

2

Hi all,

I'm not very 'up' on multi-threading, but I've been using detachNewThreadSelector in a couple of places to access data in a database. Unfortunately, on slower devices the first request may still be happening when I call the second... Which naturally causes a crash because both are calling the same method (which is obviously not thread-safe).

What is the best way to go about sorting a bug like this? Can I somehow queue them so that the second thread doesn't start until the first one has finished?

Thanks!

+2  A: 

You may want to have a look at NSOperation and NSOperationQueue which is an abstraction for a queue of tasks that can be run asynchronously from the main thread. If you want the NSOperationQueue to run just a NSOperation at a time (so to wait after the current task is compleate before firing the next one) you can just set the maxConcurrentOperationCount property of the queue to 1

rano
Great thanks - I was about too ask if NSOperationQueue was the right way to go. I just found this link through Stack - http://www.dribin.org/dave/blog/archives/2009/05/05/concurrent_operations/ - good starting point?
Joe
I guess so, do not forget to check the links to apple documentation I provided, the one about concurrent programming first ^^
rano
You might also want to look at Grand Central if iOS 4 is your sole target.
zneak
Yes thanks - sorry missed the last link. @zneak - can't unfortunately, this is an OS 3+ project.... Thanks
Joe
@Joe Wibble: if your question is answered sing this as the correct one
rano
Thanks - I usually wait until I've actually solved the problem before marking a problem as correct, because sometimes I'll be given the answer only to find out it's the wrong one... Admittedly this is a big one to sort though!
Joe
@Joe Wibble, yeah I know what you mean, but the higher reputation the higher the probability to see your questions answered
rano
Thanks - I'm fairly new to the "Stack" etiquette!
Joe
A: 

To extend ranos answer a bit, be sure to add operations from the same thread because if you add several NSOperations from several threads, they will run concurrently, even though maxConcurrentOperationCount on NSOperationQueue is set to 1.

TheBlack