Skip to content
This repository has been archived by the owner on Feb 2, 2023. It is now read-only.

[ASRunLoopQueue] Add custom run loop source to signal if jobs are still enqueued, to guarantee another runloop turn. #1397

Merged
merged 2 commits into from
Mar 18, 2016
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions AsyncDisplayKit/ASRunLoopQueue.mm
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,17 @@
#import "ASRunLoopQueue.h"
#import "ASThread.h"

#import <cstdlib>
#import <deque>

static void runLoopSourceCallback(void *info) {
// No-op
}

@interface ASRunLoopQueue () {
CFRunLoopRef _runLoop;
CFRunLoopObserverRef _runLoopObserver;
CFRunLoopSourceRef _runLoopSource;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Interesting observation: neither of these actually need to be instance variables, and could instead be static global variables. I don't think this is a big issue right now, but when we support deallocation in more places and find more use cases, it might be nice to eventually consolidate these. Don't worry about it now.

std::deque<id> _internalQueue;
ASDN::RecursiveMutex _internalQueueLock;
}
Expand All @@ -36,12 +42,26 @@ - (instancetype)initWithRunLoop:(CFRunLoopRef)runloop andHandler:(void(^)(id deq
};
_runLoopObserver = CFRunLoopObserverCreateWithHandler(NULL, kCFRunLoopBeforeWaiting, true, 0, handlerBlock);
CFRunLoopAddObserver(_runLoop, _runLoopObserver, kCFRunLoopCommonModes);

// It is not guaranteed that the runloop will turn if it has no scheduled work, and this causes processing of
// the queue to stop. Attaching a custom loop source to the run loop and signal it if new work needs to be done
CFRunLoopSourceContext *runLoopSourceContext = (CFRunLoopSourceContext *)calloc(1, sizeof(CFRunLoopSourceContext));
runLoopSourceContext->perform = runLoopSourceCallback;
_runLoopSource = CFRunLoopSourceCreate(NULL, 0, runLoopSourceContext);
CFRunLoopAddSource(runloop, _runLoopSource, kCFRunLoopCommonModes);
free(runLoopSourceContext);
}
return self;
}

- (void)dealloc
{
if (CFRunLoopContainsSource(_runLoop, _runLoopSource, kCFRunLoopCommonModes)) {
CFRunLoopRemoveSource(_runLoop, _runLoopSource, kCFRunLoopCommonModes);
}
CFRelease(_runLoopSource);
_runLoopSource = nil;

if (CFRunLoopObserverIsValid(_runLoopObserver)) {
CFRunLoopObserverInvalidate(_runLoopObserver);
}
Expand Down Expand Up @@ -103,6 +123,9 @@ - (void)enqueue:(id)object

if (!foundObject) {
_internalQueue.push_back(object);

CFRunLoopSourceSignal(_runLoopSource);
CFRunLoopWakeUp(_runLoop);
}
}

Expand Down