task_runner.h 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. // Copyright 2015 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. #ifndef CHROMECAST_PUBLIC_TASK_RUNNER_H_
  5. #define CHROMECAST_PUBLIC_TASK_RUNNER_H_
  6. #include <stdint.h>
  7. namespace chromecast {
  8. // Provides a way for vendor libraries to run code on a specific thread.
  9. // For example, cast_shell supplies an implementation of this interface through
  10. // media APIs (see MediaPipelineDeviceParams) to allow media backends to
  11. // schedule tasks to be run on the media thread.
  12. class TaskRunner {
  13. public:
  14. // Subclass and implement 'Run' to supply code to be run by PostTask or
  15. // PostDelayedTask. They both take ownership of the Task object passed in
  16. // and will delete after running the Task.
  17. class Task {
  18. public:
  19. virtual ~Task() {}
  20. virtual void Run() = 0;
  21. };
  22. // This class is intended for use with base callback type. A template has been
  23. // used to avoid introducing a hard dependency on Chromium base. It is used to
  24. // convert a chromium-style callback to a Task as defined above.
  25. template <typename T>
  26. class CallbackTask : public Task {
  27. public:
  28. CallbackTask(T callback) : callback_(std::move(callback)) {}
  29. ~CallbackTask() override = default;
  30. private:
  31. // TaskRunner::Task overrides:
  32. void Run() override { std::move(callback_).Run(); }
  33. T callback_;
  34. };
  35. // Posts a task to the thread's task queue. Delay of 0 could mean task
  36. // runs immediately (within the call to PostTask, if it's called on the
  37. // target thread) but there also could be some delay (the task could be added
  38. // to target thread's task queue).
  39. virtual bool PostTask(Task* task, uint64_t delay_milliseconds) = 0;
  40. protected:
  41. virtual ~TaskRunner() {}
  42. };
  43. } // namespace chromecast
  44. #endif // CHROMECAST_PUBLIC_TASK_RUNNER_H_