Race condition on events callbacks

The event callbacks have been rewritten with dispatch as

static void HandleMediaParsedChanged(const libvlc_event_t * event, void * self)
{
    @autoreleasepool {
        VLCMedia *media = (__bridge VLCMedia *)self;
        dispatch_async(dispatch_get_main_queue(), ^{
            [media parsedChanged];
        });
    }
}

However:

  • application can reach [obj dealloc] anytime
  • dealloc will wait on callbacks being executed at the libvlc_event_detach location (libvlc event manager thread)
  • the handler for the event will have a reference on media even if [media dealloc] is being called in another thread
  • when dispatch_async ends (but the block is not yet executed), the [media dealloc] will continue and terminate
  • the block will be executed with an invalid media reference

It leads to crash in those rare interleavings.