• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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.
4 
5 #include "extensions/common/one_shot_event.h"
6 
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"
11 
12 using base::TaskRunner;
13 
14 namespace extensions {
15 
16 struct OneShotEvent::TaskInfo {
TaskInfoextensions::OneShotEvent::TaskInfo17   TaskInfo() {}
TaskInfoextensions::OneShotEvent::TaskInfo18   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.
23   }
24   tracked_objects::Location from_here;
25   scoped_refptr<TaskRunner> runner;
26   base::Closure task;
27 };
28 
OneShotEvent()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();
33 }
~OneShotEvent()34 OneShotEvent::~OneShotEvent() {}
35 
Post(const tracked_objects::Location & from_here,const base::Closure & task) const36 void OneShotEvent::Post(const tracked_objects::Location& from_here,
37                         const base::Closure& task) const {
38   Post(from_here, task, base::MessageLoopProxy::current());
39 }
40 
Post(const tracked_objects::Location & from_here,const base::Closure & task,const scoped_refptr<TaskRunner> & runner) const41 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());
45 
46   if (is_signaled()) {
47     runner->PostTask(from_here, task);
48   } else {
49     tasks_.push_back(TaskInfo(from_here, runner, task));
50   }
51 }
52 
Signal()53 void OneShotEvent::Signal() {
54   DCHECK(thread_checker_.CalledOnValidThread());
55 
56   CHECK(!signaled_) << "Only call Signal once.";
57 
58   signaled_ = true;
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.
62 
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);
67   }
68 }
69 
70 }  // namespace extensions
71