1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "extensions/common/one_shot_event.h"
7 #include "base/callback.h"
8 #include "base/location.h"
9 #include "base/message_loop/message_loop_proxy.h"
10 #include "base/task_runner.h"
12 using base::TaskRunner
;
14 namespace extensions
{
16 struct OneShotEvent::TaskInfo
{
18 TaskInfo(const tracked_objects::Location
& from_here
,
19 const scoped_refptr
<TaskRunner
>& runner
,
20 const base::Closure
& task
)
21 : from_here(from_here
), runner(runner
), task(task
) {
22 CHECK(runner
.get()); // Detect mistakes with a decent stack frame.
24 tracked_objects::Location from_here
;
25 scoped_refptr
<TaskRunner
> runner
;
29 OneShotEvent::OneShotEvent() : signaled_(false) {
30 // It's acceptable to construct the OneShotEvent on one thread, but
31 // immediately move it to another thread.
32 thread_checker_
.DetachFromThread();
34 OneShotEvent::~OneShotEvent() {}
36 void OneShotEvent::Post(const tracked_objects::Location
& from_here
,
37 const base::Closure
& task
) const {
38 Post(from_here
, task
, base::MessageLoopProxy::current());
41 void OneShotEvent::Post(const tracked_objects::Location
& from_here
,
42 const base::Closure
& task
,
43 const scoped_refptr
<TaskRunner
>& runner
) const {
44 DCHECK(thread_checker_
.CalledOnValidThread());
47 runner
->PostTask(from_here
, task
);
49 tasks_
.push_back(TaskInfo(from_here
, runner
, task
));
53 void OneShotEvent::Signal() {
54 DCHECK(thread_checker_
.CalledOnValidThread());
56 CHECK(!signaled_
) << "Only call Signal once.";
59 // After this point, a call to Post() from one of the queued tasks
60 // could proceed immediately, but the fact that this object is
61 // single-threaded prevents that from being relevant.
63 // We could randomize tasks_ in debug mode in order to check that
64 // the order doesn't matter...
65 for (size_t i
= 0; i
< tasks_
.size(); ++i
) {
66 tasks_
[i
].runner
->PostTask(tasks_
[i
].from_here
, tasks_
[i
].task
);
70 } // namespace extensions