Skip to content

Instantly share code, notes, and snippets.

@TonnyXu
Created August 7, 2012 06:23
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TonnyXu/3282333 to your computer and use it in GitHub Desktop.
Save TonnyXu/3282333 to your computer and use it in GitHub Desktop.
Using GCD to let a thread/queue wait, an alternative way for `sleep(n)`

Before GCD

Almost the only option for us is sleep(n) (if you are familiar with SIGNAL, you can also use it). We are familiar with it, so let's pass it.

After GCD

There is resource called semaphore, use it can make your code more robust and more efficient.

  NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://www.google.com"]];
  [request setHTTPShouldUsePipelining:YES];
  NSOperationQueue *queue = [[NSOperationQueue alloc] init];
  
  dispatch_semaphore_t sema = dispatch_semaphore_create(0);
  [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *resp, NSData *data, NSError *error) {
    NSLog(@"Data: %@", data);
    dispatch_semaphore_signal(sema);
  }];
  
  dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
  dispatch_release(sema);
  NSLog(@"Over");

Please note that program will stop at dispatch_semaphore_wait.

Use it in your test code, make your test more fast and more robust. ;)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment