Search code examples
metal

Does semaphore use in triple buffering example block the main thread?


Looking at the code provided by Apple for triple buffering of Metal buffer and texture resources, it seems very strange that the use of a semaphore could block the main thread in code like the following. This is from CPU and GPU Synchronization.

- (void)drawInMTKView:(nonnull MTKView *)view
{
  dispatch_semaphore_t inFlightSemaphore = self.inFlightSemaphore;
  dispatch_semaphore_wait(inFlightSemaphore, DISPATCH_TIME_FOREVER);

  id <MTLCommandBuffer> commandBuffer = [mrc.commandQueue commandBuffer];

  __block dispatch_semaphore_t block_sema = inFlightSemaphore;
  [commandBuffer addCompletedHandler:^(id<MTLCommandBuffer> buffer)
   {
     dispatch_semaphore_signal(block_sema);
   }];

  // Metal render commands
}

How would invoking dispatch_semaphore_wait() not block the main thread in a call to drawInMTKView?


Solution

  • It absolutely can block the drawing thread, but in most applications this should happen rarely, if at all. When drawing is being driven by a display link, as is the case by default with MTKView, draw callbacks arrive every ~16ms. Since the counting semaphore allows up to three frames to be encoded before blocking, the first of these frames is almost certain to have finished executing (i.e., within 50 ms) before a subsequent frame callback arrives, and therefore the wait call doesn't entail a block. If encoding or execution takes on average longer than the nominal frame duration, the wait call will block until the most recent non-completed frame completes.