Skip to content

Instantly share code, notes, and snippets.

@EricRahm
Created October 6, 2015 21:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EricRahm/f496163343fc9321ce21 to your computer and use it in GitHub Desktop.
Save EricRahm/f496163343fc9321ce21 to your computer and use it in GitHub Desktop.
lambdas, oh my
LocallyDefinedMemoryReporter::CollectReports(...) {
// grab refs for stuff to shove in the lambda
nsCOMPtr<nsIHandleReportCallback> handleReport = aHandleReport;
nsCOMPtr<nsISupports> data = aData;
// this is defined elsewhere, we want it to hit the callback when it's refs drop to 0
nsRefPtr<MediaDecoder::ResourceSizes> resourceSizes = new MediaDecoder::ResourceSizes(MediaMemoryTracker::MallocSizeOf);
nsCOMPtr<nsIRunnable> callback = NS_NewRunnableFunction([handleReport, data, resourceSizes] () {
// NOTE: referencing resourcesSizes causes a cycle, so it's ref count will never go to 0
// so my goal is to not do that, preferably this function would be something like:
// [handleReport, data] (size_t size) { ... }
handleReport->Callback(EmptyCString(), NS_LITERAL_CSTRING("explicit/media/resources"),
KIND_HEAP, UNITS_BYTES, resourceSizes->mByteSize,
NS_LITERAL_CSTRING("Memory used by media resources including streaming buffers, caches, etc."),
data);
nsCOMPtr<nsIMemoryReporterManager> imgr =
do_GetService("@mozilla.org/memory-reporter-manager;1");
if (imgr) {
imgr->EndReport();
}
});
foreach(auto thing : stuff) {
thing->measureAsyncMemory(resourceSizes)
}
}
// and then ResourceSizes is defined elsewhere:
// Helper struct for accumulating resource sizes that need to be measured
// asynchronously. Once all references are dropped the callback will be
// invoked.
struct ResourceSizes
{
NS_INLINE_DECL_THREADSAFE_REFCOUNTING(ResourceSizes)
ResourceSizes(MallocSizeOf aMallocSizeOf)
: mMallocSizeOf(aMallocSizeOf)
, mByteSize(0)
, mCallback()
{
}
~ResourceSizes()
{
// Notify the main thread that the async operation is complete.
nsCOMPtr<nsIRunnable> completion(mCallback);
AbstractThread::MainThread()->Dispatch(completion.forget());
}
mozilla::MallocSizeOf mMallocSizeOf;
mozilla::Atomic<size_t> mByteSize;
nsCOMPtr<nsIRunnable> mCallback;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment