Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

metal

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?

like image 842
MoDJ Avatar asked Oct 20 '25 04:10

MoDJ


1 Answers

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.

like image 133
warrenm Avatar answered Oct 22 '25 04:10

warrenm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!