title: iOS -- persuade an NSOperation to yield to other threads before starting a long and apparently unbreakable task?
body: <p>I have a low-priority PDF-drawing NSOperation.  I am using the function CGContextDrawPDFPage to draw the page.  </p>
  
  <p>As best I can tell, the app will not switch to another thread while the CGContextDrawPDFPage function is executing.  I suppose I need to break up my graphics context into several smaller contexts to get around that.  But I still have one problem -- how can I persuade the operation to allow other threads to perform their tasks before starting that draw?  The way things are set up right now, the app draws the page right away, even though the thread priority is set to zero.</p>
  
  <p>Here is the code that adds the NSOperation to the queue:</p>
  
  <pre><code>MyNSOperationSubclass* op = [[MyNSOperationSubclass alloc]initWithStuff: stuff];
  [op setThreadPriority:0.];
  [self.drawingQueue addOperation:op];
  </code></pre>
  
  <p>Here is some code within MyNSOperationSubclass:</p>
  
  <pre><code>-(void) drawStuff {
      NSLog(@"drawStuff");
      @autoreleasepool {
          // some code to setup the graphics context and PDF page here
          CGContextDrawPDFPage(context, page);
          [self finish];  // finishes the NSOperation
      }   
  }
  
  -(void) main {
      NSLog(@"main");
      @autoreleasepool {
          [self drawStuff];
      }
  
  }
  
  -(void) start {
      self.isExecuting = YES;
      [NSThread detachNewThreadSelector:@selector(main) toTarget:self withObject:nil];
  }
  </code></pre>
  
  <p>what happens is that even though the thread priority is set to zero, the setup code is so quick that the NSOperation gets into the CGContextDrawPDFPage call right as the operation is started.  But  once that call has started, the thread won't yield to other threads until it has finished.  So the drawing operation happens right away, which is the opposite of what I want to do.</p>
  
  <p>EDIT:  After taking a closer look, the first answerer is correct that the CGContextDrawPDFPage call does not always prevent a thread from yielding.  But even with a non-concurrent operation, I still have the problem that it finishes quickly, rather than waiting around for other, higher-priority stuff to happen.</p>
  
  <p>EDIT 2:  Apparently I don't understand how thread priorities work.  After changing it to a nonconcurrent operation, the thread priority of the operation thread is 0.5, even though I called [op setThreadPriority: 0] before adding it to the queue.</p>