ryu1
12/4/2017 - 10:56 AM

Objective-C Snippet

+ (void)runCriticalSection:(void (^)(void))func
{
    static dispatch_semaphore_t sema; // The semaphore
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        // Initialize with count=1 (this is executed only once):
        sema = dispatch_semaphore_create(1);
    });

    // Try to decrement the semaphore. This succeeds if the count is still 1
    // (meaning that runCriticalSection is not executing), and fails if the
    // current count is 0 (meaning that runCriticalSection is executing):
    if (dispatch_semaphore_wait(sema, DISPATCH_TIME_NOW) == 0) {
        // Success, semaphore count is now 0.
        // Start asynchronous operation.
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //critical code
            func();
            // Increment the semaphore count (from 0 to 1), so that the next call
            // to applicationDidBecomeActive will start a new operation:
            dispatch_semaphore_signal(sema);
        });
    }
}