Skip to content

Instantly share code, notes, and snippets.

@steipete
Last active March 26, 2019 09:39
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save steipete/3e781cf061ff166eb5622d4d275da84c to your computer and use it in GitHub Desktop.
Save steipete/3e781cf061ff166eb5622d4d275da84c to your computer and use it in GitHub Desktop.
PSPDFApplicationIsTerminating - detect application termination on iOS and macOS. License: MIT. Taken out of the commercial PSPDFKit PDF SDK. http://pspdfkit.com
static _Atomic(BOOL) _applicationWillTerminate = NO;
__attribute__((constructor)) static void PSPDFInstallAppWillTerminateHandler(void) {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
[NSNotificationCenter.defaultCenter addObserverForName:UIApplicationWillTerminateNotification object:nil queue:nil usingBlock:^(NSNotification *note) {
_applicationWillTerminate = YES;
PSPDFLogWarning(@"Application shutdown event detected.");
}];
});
}
PSPDF_EXTERN BOOL PSPDFApplicationIsTerminating(void) {
return _applicationWillTerminate;
}
@LeoNatan
Copy link

Interesting about _Atomic. When is it safe to just assign, vs using atomic_store()?

@steipete
Copy link
Author

@LeoNatan AFAIK, default variable access changes it with sequential consistency. atomic_store and other intrinsics can be used for a more relaxed memory access.

Finding good docs about that is hard:
https://en.cppreference.com/w/c/language/atomic
http://www.informit.com/articles/article.aspx?p=1832575&seqNum=4

@LeoNatan
Copy link

LeoNatan commented Dec 11, 2018

The worst that can happen by specifying sequentially consistent is a performance penalty. The worst that can happen when you specify a more relaxed ordering than you meant to have is that your code is subtly wrong. Worst of all, if you test it on a strongly ordered architecture such as x86, it's likely to work — and then subtly fail when you port it to something like ARM.

Ouch! TIL indeed!
Thanks!

@LeoNatan
Copy link

LeoNatan commented Dec 11, 2018

I got confused for a second. It's been a while since I used atomic_fetch_add/atomic_fetch_sub. Is the default relax order relaxed?


If I understand correctly, what I really want is memory_order_seq_cst, which is then the order that is used by _Atomic(XXX), which also has a nicer syntax.

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