ruipacheco
ruipacheco

Reputation: 16472

Wait for flag from background thread

Upon starting my program I fire a second thread to do some background work. This thread will never die but I need to wait for it to finish what it's doing before allowing the main thread to continue.

How can I block and resume the main thread while I wait for the second thread to update it's status?

Upvotes: 2

Views: 1089

Answers (1)

bbum
bbum

Reputation: 162722

First, don't block the main thread. Not ever. Blocking the main thread long enough on iOS will cause your app to be killed. On OS X, it'll cause the rainbow pizza of death to show up.

Ultimately, blocking the main thread causes your app to be unresponsive.

Instead, have the application throw up a modal dialog or modal sheet or some other status indicator that indicates that the app is doing something that must be done before progress continues. Make sure the "quit" menu item is still enabled in case the user decides "oh, crap! no time for this! abort! abort! abort!".

Then, when your background thread is done, use any of the various mechanisms to dispatch to the main thread (GCD, performSelector:..., etc...) that then makes the "initializing" modality go away.

No need to poll, sleep, or while(){} at all.


My background thread isn't done, it lives more or less forever. And I need it to reach a certain state before the main thread can do it's thing.

Exactly; so, when it reaches that state, you could use:

 [someObject performSelectorOnMainThread:@selector(sshConnectionEstablished:) withObject:nil];

Where someObject might likely be your application delegate.

Or you could use notifications and do something like:

 dispatch_async(dispatch_get_main_queue(), ^{
    [[NSNotificationCenter defaultCenter] postNotificationNamed:@"MySSHConnectionEstablished" ....];
 });

Note that whether you want it to be async or sync is up to you.

Upvotes: 7

Related Questions