Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to let a thread A wait until thread B is finished, then continue thread A?
    primarykey
    data
    text
    <p>Within a thread A I call an asynchronous service, which runs in thread B. The service calls a delegate method once finished. I want thread A to wait until thread B finishes. I used NSCondition for this.</p> <p>This is my set up (skipped the unimportant stuff):</p> <pre><code>-(void)load { self.someCheckIsTrue = YES; self.condition = [[NSCondition alloc] init]; [self.condition lock]; NSLog(@"log1"); Service *service = // set up service [service request:url delegate:self didFinishSelector:@selector(response:)]; while (self.someCheckIsTrue) [self.condition wait]; NSLog(@"log3"); [self.condition unlock]; } -(void)response:(id)data { NSLog(@"log2"); [self.condition lock]; self.someCheckIsTrue = NO; // do something with the response, doesn't matter here [self.condition signal]; [self.condition unlock]; } </code></pre> <p>For some reason, only "log1" is printed, neither "log2" nor "log3". I assume it's why the delegate method <strong>response</strong> is called by the "service thread", which is thread B, whereas <strong>load</strong> is called by thread A.</p> <p>I also tried a Semaphore, but doesn't work either. Here is the code:</p> <pre><code>-(void)load { NSLog(@"log1"); Service *service = // set up service self.sema = dispatch_semaphore_create(0); [service request:url delegate:self didFinishSelector:@selector(response:)]; dispatch_semaphore_wait(self.sema, DISPATCH_TIME_FOREVER); NSLog(@"log3"); } -(void)response:(id)data { NSLog(@"log2"); // do something with the response, doesn't matter here dispatch_semaphore_signal(self.sema); } </code></pre> <p>How can I get this to work?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload