Index: media/base/callback_util.cc |
diff --git a/media/base/callback_util.cc b/media/base/callback_util.cc |
new file mode 100644 |
index 0000000000000000000000000000000000000000..010e0809b2e4ccded2171cfdbbe901aa217cb5d2 |
--- /dev/null |
+++ b/media/base/callback_util.cc |
@@ -0,0 +1,66 @@ |
+// Copyright (c) 2012 The Chromium Authors. All rights reserved. |
+// Use of this source code is governed by a BSD-style license that can be |
+// found in the LICENSE file. |
+ |
+#include "media/base/callback_util.h" |
+ |
+#include "base/bind.h" |
+#include "base/memory/ref_counted.h" |
+ |
+namespace media { |
+ |
+namespace { |
acolwell GONE FROM CHROMIUM
2012/07/19 00:58:18
remove per our discussion.
scherkus (not reviewing)
2012/07/19 21:29:02
Done.
|
+ |
+// Executes a callback when all references to the object have been |
+// released. We use reference counting as it already implements a thread safe |
+// counter and avoids the use of base::Unretained() and delete this, which may |
+// lead to use-after-free if clients retain closures after executing them. |
+class CountingCB : public base::RefCountedThreadSafe<CountingCB> { |
+ public: |
+ CountingCB(const base::Closure& done_cb) |
acolwell GONE FROM CHROMIUM
2012/07/19 00:58:18
explicit
scherkus (not reviewing)
2012/07/19 21:29:02
Done.
|
+ : done_cb_(done_cb) { |
+ } |
+ |
+ // Returns a closure bound to this object. |
+ base::Closure GetClosure() { |
+ return base::Bind(&CountingCB::DoNothing, this); |
+ } |
+ |
+ protected: |
+ friend class base::RefCountedThreadSafe<CountingCB>; |
+ virtual ~CountingCB() { |
+ done_cb_.Run(); |
+ } |
+ |
+ private: |
+ void DoNothing() {} |
+ |
+ base::Closure done_cb_; |
+ |
+ DISALLOW_COPY_AND_ASSIGN(CountingCB); |
+}; |
+ |
+} // namespace |
+ |
+void RunInSeries(scoped_ptr<std::queue<ClosureCB> > closures, |
+ const base::Closure& done_cb) { |
+ if (closures->empty()) { |
+ done_cb.Run(); |
+ return; |
+ } |
+ |
+ ClosureCB cb = closures->front(); |
+ closures->pop(); |
+ cb.Run(base::Bind(&RunInSeries, base::Passed(&closures), done_cb)); |
+} |
+ |
+void RunInParallel(scoped_ptr<std::queue<ClosureCB> > closures, |
+ const base::Closure& done_cb) { |
+ scoped_refptr<CountingCB> counting_cb = new CountingCB(done_cb); |
+ while (!closures->empty()) { |
+ closures->front().Run(counting_cb->GetClosure()); |
+ closures->pop(); |
+ } |
+} |
+ |
+} // namespace media |