WebKit roll 98705:98715
[chromium-blink-merge.git] / base / task.h
blob7e87ff72abc4067e94190f2c459b0363707c83a2
1 // Copyright (c) 2011 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 // ============================================================================
6 // ****************************************************************************
7 // * THIS HEADER IS DEPRECATED, SEE base/callback.h FOR NEW IMPLEMENTATION *
8 // ****************************************************************************
9 // ============================================================================
10 // ============================================================================
11 // ****************************************************************************
12 // * THIS HEADER IS DEPRECATED, SEE base/callback.h FOR NEW IMPLEMENTATION *
13 // ****************************************************************************
14 // ============================================================================
15 // ============================================================================
16 // ****************************************************************************
17 // * THIS HEADER IS DEPRECATED, SEE base/callback.h FOR NEW IMPLEMENTATION *
18 // ****************************************************************************
19 // ============================================================================
20 // ============================================================================
21 // ****************************************************************************
22 // * THIS HEADER IS DEPRECATED, SEE base/callback.h FOR NEW IMPLEMENTATION *
23 // ****************************************************************************
24 // ============================================================================
25 // ============================================================================
26 // ****************************************************************************
27 // * THIS HEADER IS DEPRECATED, SEE base/callback.h FOR NEW IMPLEMENTATION *
28 // ****************************************************************************
29 // ============================================================================
30 #ifndef BASE_TASK_H_
31 #define BASE_TASK_H_
32 #pragma once
34 #include "base/base_export.h"
35 #include "base/callback.h"
36 #include "base/debug/alias.h"
37 #include "base/memory/raw_scoped_refptr_mismatch_checker.h"
38 #include "base/memory/weak_ptr.h"
39 #include "base/tuple.h"
41 namespace base {
42 const size_t kDeadTask = 0xDEAD7A53;
45 // Task ------------------------------------------------------------------------
47 // A task is a generic runnable thingy, usually used for running code on a
48 // different thread or for scheduling future tasks off of the message loop.
50 class BASE_EXPORT Task {
51 public:
52 Task();
53 virtual ~Task();
55 // Tasks are automatically deleted after Run is called.
56 virtual void Run() = 0;
59 class BASE_EXPORT CancelableTask : public Task {
60 public:
61 CancelableTask();
62 virtual ~CancelableTask();
64 // Not all tasks support cancellation.
65 virtual void Cancel() = 0;
68 // Scoped Factories ------------------------------------------------------------
70 // These scoped factory objects can be used by non-refcounted objects to safely
71 // place tasks in a message loop. Each factory guarantees that the tasks it
72 // produces will not run after the factory is destroyed. Commonly, factories
73 // are declared as class members, so the class' tasks will automatically cancel
74 // when the class instance is destroyed.
76 // Exampe Usage:
78 // class MyClass {
79 // private:
80 // // This factory will be used to schedule invocations of SomeMethod.
81 // ScopedRunnableMethodFactory<MyClass> some_method_factory_;
83 // public:
84 // // It is safe to suppress warning 4355 here.
85 // MyClass() : ALLOW_THIS_IN_INITIALIZER_LIST(some_method_factory_(this)) { }
87 // void SomeMethod() {
88 // // If this function might be called directly, you might want to revoke
89 // // any outstanding runnable methods scheduled to call it. If it's not
90 // // referenced other than by the factory, this is unnecessary.
91 // some_method_factory_.RevokeAll();
92 // ...
93 // }
95 // void ScheduleSomeMethod() {
96 // // If you'd like to only only have one pending task at a time, test for
97 // // |empty| before manufacturing another task.
98 // if (!some_method_factory_.empty())
99 // return;
101 // // The factories are not thread safe, so always invoke on
102 // // |MessageLoop::current()|.
103 // MessageLoop::current()->PostDelayedTask(
104 // FROM_HERE,
105 // some_method_factory_.NewRunnableMethod(&MyClass::SomeMethod),
106 // kSomeMethodDelayMS);
107 // }
108 // };
110 // A ScopedRunnableMethodFactory creates runnable methods for a specified
111 // object. This is particularly useful for generating callbacks for
112 // non-reference counted objects when the factory is a member of the object.
113 template<class T>
114 class ScopedRunnableMethodFactory {
115 public:
116 explicit ScopedRunnableMethodFactory(T* object) : weak_factory_(object) {
119 template <class Method>
120 inline CancelableTask* NewRunnableMethod(Method method) {
121 return new RunnableMethod<Method, Tuple0>(
122 weak_factory_.GetWeakPtr(), method, MakeTuple());
125 template <class Method, class A>
126 inline CancelableTask* NewRunnableMethod(Method method, const A& a) {
127 return new RunnableMethod<Method, Tuple1<A> >(
128 weak_factory_.GetWeakPtr(), method, MakeTuple(a));
131 template <class Method, class A, class B>
132 inline CancelableTask* NewRunnableMethod(Method method, const A& a,
133 const B& b) {
134 return new RunnableMethod<Method, Tuple2<A, B> >(
135 weak_factory_.GetWeakPtr(), method, MakeTuple(a, b));
138 template <class Method, class A, class B, class C>
139 inline CancelableTask* NewRunnableMethod(Method method,
140 const A& a,
141 const B& b,
142 const C& c) {
143 return new RunnableMethod<Method, Tuple3<A, B, C> >(
144 weak_factory_.GetWeakPtr(), method, MakeTuple(a, b, c));
147 template <class Method, class A, class B, class C, class D>
148 inline CancelableTask* NewRunnableMethod(Method method,
149 const A& a,
150 const B& b,
151 const C& c,
152 const D& d) {
153 return new RunnableMethod<Method, Tuple4<A, B, C, D> >(
154 weak_factory_.GetWeakPtr(), method, MakeTuple(a, b, c, d));
157 template <class Method, class A, class B, class C, class D, class E>
158 inline CancelableTask* NewRunnableMethod(Method method,
159 const A& a,
160 const B& b,
161 const C& c,
162 const D& d,
163 const E& e) {
164 return new RunnableMethod<Method, Tuple5<A, B, C, D, E> >(
165 weak_factory_.GetWeakPtr(), method, MakeTuple(a, b, c, d, e));
168 void RevokeAll() { weak_factory_.InvalidateWeakPtrs(); }
170 bool empty() const { return !weak_factory_.HasWeakPtrs(); }
172 protected:
173 template <class Method, class Params>
174 class RunnableMethod : public CancelableTask {
175 public:
176 RunnableMethod(const base::WeakPtr<T>& obj,
177 Method meth,
178 const Params& params)
179 : obj_(obj),
180 meth_(meth),
181 params_(params) {
182 COMPILE_ASSERT(
183 (base::internal::ParamsUseScopedRefptrCorrectly<Params>::value),
184 badscopedrunnablemethodparams);
187 virtual void Run() {
188 if (obj_)
189 DispatchToMethod(obj_.get(), meth_, params_);
192 virtual void Cancel() {
193 obj_.reset();
196 private:
197 base::WeakPtr<T> obj_;
198 Method meth_;
199 Params params_;
201 DISALLOW_COPY_AND_ASSIGN(RunnableMethod);
204 private:
205 base::WeakPtrFactory<T> weak_factory_;
208 // General task implementations ------------------------------------------------
210 // Task to delete an object
211 template<class T>
212 class DeleteTask : public CancelableTask {
213 public:
214 explicit DeleteTask(const T* obj) : obj_(obj) {
216 virtual void Run() {
217 delete obj_;
219 virtual void Cancel() {
220 obj_ = NULL;
223 private:
224 const T* obj_;
227 // Task to Release() an object
228 template<class T>
229 class ReleaseTask : public CancelableTask {
230 public:
231 explicit ReleaseTask(const T* obj) : obj_(obj) {
233 virtual void Run() {
234 if (obj_)
235 obj_->Release();
237 virtual void Cancel() {
238 obj_ = NULL;
241 private:
242 const T* obj_;
245 // Equivalents for use by base::Bind().
246 template<typename T>
247 void DeletePointer(T* obj) {
248 delete obj;
251 template<typename T>
252 void ReleasePointer(T* obj) {
253 obj->Release();
256 // RunnableMethodTraits --------------------------------------------------------
258 // This traits-class is used by RunnableMethod to manage the lifetime of the
259 // callee object. By default, it is assumed that the callee supports AddRef
260 // and Release methods. A particular class can specialize this template to
261 // define other lifetime management. For example, if the callee is known to
262 // live longer than the RunnableMethod object, then a RunnableMethodTraits
263 // struct could be defined with empty RetainCallee and ReleaseCallee methods.
265 // The DISABLE_RUNNABLE_METHOD_REFCOUNT macro is provided as a convenient way
266 // for declaring a RunnableMethodTraits that disables refcounting.
268 template <class T>
269 struct RunnableMethodTraits {
270 RunnableMethodTraits() {
271 #ifndef NDEBUG
272 origin_thread_id_ = base::PlatformThread::CurrentId();
273 #endif
276 ~RunnableMethodTraits() {
277 #ifndef NDEBUG
278 // If destroyed on a separate thread, then we had better have been using
279 // thread-safe reference counting!
280 if (origin_thread_id_ != base::PlatformThread::CurrentId())
281 DCHECK(T::ImplementsThreadSafeReferenceCounting());
282 #endif
285 void RetainCallee(T* obj) {
286 #ifndef NDEBUG
287 // Catch NewRunnableMethod being called in an object's constructor. This
288 // isn't safe since the method can be invoked before the constructor
289 // completes, causing the object to be deleted.
290 obj->AddRef();
291 obj->Release();
292 #endif
293 obj->AddRef();
296 void ReleaseCallee(T* obj) {
297 obj->Release();
300 private:
301 #ifndef NDEBUG
302 base::PlatformThreadId origin_thread_id_;
303 #endif
306 // Convenience macro for declaring a RunnableMethodTraits that disables
307 // refcounting of a class. This is useful if you know that the callee
308 // will outlive the RunnableMethod object and thus do not need the ref counts.
310 // The invocation of DISABLE_RUNNABLE_METHOD_REFCOUNT should be done at the
311 // global namespace scope. Example:
313 // namespace foo {
314 // class Bar {
315 // ...
316 // };
317 // } // namespace foo
319 // DISABLE_RUNNABLE_METHOD_REFCOUNT(foo::Bar);
321 // This is different from DISALLOW_COPY_AND_ASSIGN which is declared inside the
322 // class.
323 #define DISABLE_RUNNABLE_METHOD_REFCOUNT(TypeName) \
324 template <> \
325 struct RunnableMethodTraits<TypeName> { \
326 void RetainCallee(TypeName* manager) {} \
327 void ReleaseCallee(TypeName* manager) {} \
330 // RunnableMethod and RunnableFunction -----------------------------------------
332 // Runnable methods are a type of task that call a function on an object when
333 // they are run. We implement both an object and a set of NewRunnableMethod and
334 // NewRunnableFunction functions for convenience. These functions are
335 // overloaded and will infer the template types, simplifying calling code.
337 // The template definitions all use the following names:
338 // T - the class type of the object you're supplying
339 // this is not needed for the Static version of the call
340 // Method/Function - the signature of a pointer to the method or function you
341 // want to call
342 // Param - the parameter(s) to the method, possibly packed as a Tuple
343 // A - the first parameter (if any) to the method
344 // B - the second parameter (if any) to the method
346 // Put these all together and you get an object that can call a method whose
347 // signature is:
348 // R T::MyFunction([A[, B]])
350 // Usage:
351 // PostTask(FROM_HERE, NewRunnableMethod(object, &Object::method[, a[, b]])
352 // PostTask(FROM_HERE, NewRunnableFunction(&function[, a[, b]])
354 // RunnableMethod and NewRunnableMethod implementation -------------------------
356 template <class T, class Method, class Params>
357 class RunnableMethod : public CancelableTask {
358 public:
359 RunnableMethod(T* obj, Method meth, const Params& params)
360 : obj_(obj), meth_(meth), params_(params) {
361 traits_.RetainCallee(obj_);
362 COMPILE_ASSERT(
363 (base::internal::ParamsUseScopedRefptrCorrectly<Params>::value),
364 badrunnablemethodparams);
367 ~RunnableMethod() {
368 ReleaseCallee();
369 obj_ = reinterpret_cast<T*>(base::kDeadTask);
372 virtual void Run() {
373 if (obj_)
374 DispatchToMethod(obj_, meth_, params_);
377 virtual void Cancel() {
378 ReleaseCallee();
381 private:
382 void ReleaseCallee() {
383 T* obj = obj_;
384 obj_ = NULL;
385 if (obj)
386 traits_.ReleaseCallee(obj);
389 T* obj_;
390 Method meth_;
391 Params params_;
392 RunnableMethodTraits<T> traits_;
395 template <class T, class Method>
396 inline CancelableTask* NewRunnableMethod(T* object, Method method) {
397 return new RunnableMethod<T, Method, Tuple0>(object, method, MakeTuple());
400 template <class T, class Method, class A>
401 inline CancelableTask* NewRunnableMethod(T* object, Method method, const A& a) {
402 return new RunnableMethod<T, Method, Tuple1<A> >(object,
403 method,
404 MakeTuple(a));
407 template <class T, class Method, class A, class B>
408 inline CancelableTask* NewRunnableMethod(T* object, Method method,
409 const A& a, const B& b) {
410 return new RunnableMethod<T, Method, Tuple2<A, B> >(object, method,
411 MakeTuple(a, b));
414 template <class T, class Method, class A, class B, class C>
415 inline CancelableTask* NewRunnableMethod(T* object, Method method,
416 const A& a, const B& b, const C& c) {
417 return new RunnableMethod<T, Method, Tuple3<A, B, C> >(object, method,
418 MakeTuple(a, b, c));
421 template <class T, class Method, class A, class B, class C, class D>
422 inline CancelableTask* NewRunnableMethod(T* object, Method method,
423 const A& a, const B& b,
424 const C& c, const D& d) {
425 return new RunnableMethod<T, Method, Tuple4<A, B, C, D> >(object, method,
426 MakeTuple(a, b,
427 c, d));
430 template <class T, class Method, class A, class B, class C, class D, class E>
431 inline CancelableTask* NewRunnableMethod(T* object, Method method,
432 const A& a, const B& b,
433 const C& c, const D& d, const E& e) {
434 return new RunnableMethod<T,
435 Method,
436 Tuple5<A, B, C, D, E> >(object,
437 method,
438 MakeTuple(a, b, c, d, e));
441 template <class T, class Method, class A, class B, class C, class D, class E,
442 class F>
443 inline CancelableTask* NewRunnableMethod(T* object, Method method,
444 const A& a, const B& b,
445 const C& c, const D& d, const E& e,
446 const F& f) {
447 return new RunnableMethod<T,
448 Method,
449 Tuple6<A, B, C, D, E, F> >(object,
450 method,
451 MakeTuple(a, b, c, d, e,
452 f));
455 template <class T, class Method, class A, class B, class C, class D, class E,
456 class F, class G>
457 inline CancelableTask* NewRunnableMethod(T* object, Method method,
458 const A& a, const B& b,
459 const C& c, const D& d, const E& e,
460 const F& f, const G& g) {
461 return new RunnableMethod<T,
462 Method,
463 Tuple7<A, B, C, D, E, F, G> >(object,
464 method,
465 MakeTuple(a, b, c, d,
466 e, f, g));
469 template <class T, class Method, class A, class B, class C, class D, class E,
470 class F, class G, class H>
471 inline CancelableTask* NewRunnableMethod(T* object, Method method,
472 const A& a, const B& b,
473 const C& c, const D& d, const E& e,
474 const F& f, const G& g, const H& h) {
475 return new RunnableMethod<T,
476 Method,
477 Tuple8<A, B, C, D, E, F, G, H> >(object,
478 method,
479 MakeTuple(a, b, c,
480 d, e, f,
481 g, h));
484 // RunnableFunction and NewRunnableFunction implementation ---------------------
486 template <class Function, class Params>
487 class RunnableFunction : public Task {
488 public:
489 RunnableFunction(Function function, const Params& params)
490 : function_(function), params_(params) {
491 COMPILE_ASSERT(
492 (base::internal::ParamsUseScopedRefptrCorrectly<Params>::value),
493 badrunnablefunctionparams);
496 ~RunnableFunction() {
497 function_ = reinterpret_cast<Function>(base::kDeadTask);
500 virtual void Run() {
501 if (function_)
502 DispatchToFunction(function_, params_);
505 private:
506 Function function_;
507 Params params_;
510 template <class Function>
511 inline Task* NewRunnableFunction(Function function) {
512 return new RunnableFunction<Function, Tuple0>(function, MakeTuple());
515 template <class Function, class A>
516 inline Task* NewRunnableFunction(Function function, const A& a) {
517 return new RunnableFunction<Function, Tuple1<A> >(function, MakeTuple(a));
520 template <class Function, class A, class B>
521 inline Task* NewRunnableFunction(Function function, const A& a, const B& b) {
522 return new RunnableFunction<Function, Tuple2<A, B> >(function,
523 MakeTuple(a, b));
526 template <class Function, class A, class B, class C>
527 inline Task* NewRunnableFunction(Function function, const A& a, const B& b,
528 const C& c) {
529 return new RunnableFunction<Function, Tuple3<A, B, C> >(function,
530 MakeTuple(a, b, c));
533 template <class Function, class A, class B, class C, class D>
534 inline Task* NewRunnableFunction(Function function, const A& a, const B& b,
535 const C& c, const D& d) {
536 return new RunnableFunction<Function, Tuple4<A, B, C, D> >(function,
537 MakeTuple(a, b,
538 c, d));
541 template <class Function, class A, class B, class C, class D, class E>
542 inline Task* NewRunnableFunction(Function function, const A& a, const B& b,
543 const C& c, const D& d, const E& e) {
544 return new RunnableFunction<Function, Tuple5<A, B, C, D, E> >(function,
545 MakeTuple(a, b,
546 c, d,
547 e));
550 template <class Function, class A, class B, class C, class D, class E,
551 class F>
552 inline Task* NewRunnableFunction(Function function, const A& a, const B& b,
553 const C& c, const D& d, const E& e,
554 const F& f) {
555 return new RunnableFunction<Function, Tuple6<A, B, C, D, E, F> >(function,
556 MakeTuple(a, b, c, d, e, f));
559 template <class Function, class A, class B, class C, class D, class E,
560 class F, class G>
561 inline Task* NewRunnableFunction(Function function, const A& a, const B& b,
562 const C& c, const D& d, const E& e, const F& f,
563 const G& g) {
564 return new RunnableFunction<Function, Tuple7<A, B, C, D, E, F, G> >(function,
565 MakeTuple(a, b, c, d, e, f, g));
568 template <class Function, class A, class B, class C, class D, class E,
569 class F, class G, class H>
570 inline Task* NewRunnableFunction(Function function, const A& a, const B& b,
571 const C& c, const D& d, const E& e, const F& f,
572 const G& g, const H& h) {
573 return new RunnableFunction<Function, Tuple8<A, B, C, D, E, F, G, H> >(
574 function, MakeTuple(a, b, c, d, e, f, g, h));
577 namespace base {
579 // ScopedTaskRunner is akin to scoped_ptr for Tasks. It ensures that the Task
580 // is executed and deleted no matter how the current scope exits.
581 class BASE_EXPORT ScopedTaskRunner {
582 public:
583 // Takes ownership of the task.
584 explicit ScopedTaskRunner(Task* task);
585 ~ScopedTaskRunner();
587 Task* Release();
589 private:
590 Task* task_;
592 DISALLOW_IMPLICIT_CONSTRUCTORS(ScopedTaskRunner);
595 class BASE_EXPORT ScopedClosureRunner {
596 public:
597 explicit ScopedClosureRunner(const Closure& closure);
598 ~ScopedClosureRunner();
600 Closure Release();
602 private:
603 Closure closure_;
605 DISALLOW_IMPLICIT_CONSTRUCTORS(ScopedClosureRunner);
608 namespace subtle {
610 // This class is meant for use in the implementation of MessageLoop classes
611 // such as MessageLoop, MessageLoopProxy, BrowserThread, and WorkerPool to
612 // implement the compatibility APIs while we are transitioning from Task to
613 // Callback.
615 // It should NOT be used anywhere else!
617 // In particular, notice that this is RefCounted instead of
618 // RefCountedThreadSafe. We rely on the fact that users of this class are
619 // careful to ensure that a lock is taken during transfer of ownership for
620 // objects from this class to ensure the refcount is not corrupted.
621 class TaskClosureAdapter : public RefCounted<TaskClosureAdapter> {
622 public:
623 explicit TaskClosureAdapter(Task* task);
625 // |should_leak_task| points to a flag variable that can be used to determine
626 // if this class should leak the Task on destruction. This is important
627 // at MessageLoop shutdown since not all tasks can be safely deleted without
628 // running. See MessageLoop::DeletePendingTasks() for the exact behavior
629 // of when a Task should be deleted. It is subtle.
630 TaskClosureAdapter(Task* task, bool* should_leak_task);
632 void Run();
634 private:
635 friend class base::RefCounted<TaskClosureAdapter>;
637 ~TaskClosureAdapter();
639 Task* task_;
640 bool* should_leak_task_;
641 static bool kTaskLeakingDefault;
644 } // namespace subtle
646 } // namespace base
648 #endif // BASE_TASK_H_