views:

26

answers:

1

hi guys, here is question:

i have 2 threads: the main one and the other.

  • on the main thread i perform anything gui related
  • on the other thread i perform all my calculations

on some operation i have to stop the second thread for some seconds, waiting the first thread to do something....

my question:

which is the best option and why? being in the second thread..

  1. use sleepUntilDate
  2. use sleep function
  3. any other option?

the pseudo code is this:

on the second thread:

... 
do some calculations
send the results to the first thread and wait for the # of seconds to wait (let's say K)
wait K seconds
A: 

+[NSThread sleepForTimeInterval:] is more likely to do what you want if the time suddenly changes. Being in the second thread doesn't affect things.

However, I don't see why the second thread should have to sleep at all. If you want to wait for new data, use something like NSCondition or NSConditionLock to signal when data has arrived.

Alternatively, don't use threads directly at all. You can use NSOperation or performSelectorInBackground: or dispatch_*, to name a few.

EDIT: You need to be very careful when writing traditional thread-synchronization code, and you need to be just as careful every time you edit it to add a new feature. I have some threaded code which I need to think about for a couple minutes to figure out what's going on. Deadlocks are no fun.

tc.
Thanks tc, I have been reading about NSOperation, seems that it's a better option.
subzero
Note that NSOperation has its own problems: If you're calculating based on user input (plotting a graph, showing search results, etc) then you might need to cancel old operations before adding new ones. Cancelling an operation only *attempts* to cancel it; it could still complete.
tc.