single_thread_task_executor.h 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // Copyright 2019 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 BASE_TASK_SINGLE_THREAD_TASK_EXECUTOR_H_
  5. #define BASE_TASK_SINGLE_THREAD_TASK_EXECUTOR_H_
  6. #include <memory>
  7. #include "base/base_export.h"
  8. #include "base/memory/scoped_refptr.h"
  9. #include "base/message_loop/message_pump_type.h"
  10. #include "base/task/simple_task_executor.h"
  11. #include "base/task/single_thread_task_runner.h"
  12. namespace base {
  13. class MessagePump;
  14. namespace sequence_manager {
  15. class SequenceManager;
  16. class TaskQueue;
  17. } // namespace sequence_manager
  18. // A simple single thread TaskExecutor intended for non-test usage. Tests should
  19. // generally use TaskEnvironment or BrowserTaskEnvironment instead.
  20. // TODO(alexclarke): Inherit from TaskExecutor to support base::Here().
  21. class BASE_EXPORT SingleThreadTaskExecutor {
  22. public:
  23. // For MessagePumpType::CUSTOM use the constructor that takes a pump.
  24. explicit SingleThreadTaskExecutor(
  25. MessagePumpType type = MessagePumpType::DEFAULT);
  26. // Creates a SingleThreadTaskExecutor pumping from a custom |pump|.
  27. // The above constructor using MessagePumpType is generally preferred.
  28. explicit SingleThreadTaskExecutor(std::unique_ptr<MessagePump> pump);
  29. SingleThreadTaskExecutor(const SingleThreadTaskExecutor&) = delete;
  30. SingleThreadTaskExecutor& operator=(const SingleThreadTaskExecutor&) = delete;
  31. // Shuts down the SingleThreadTaskExecutor, after this no tasks can be
  32. // executed and the base::TaskExecutor APIs are non-functional but won't crash
  33. // if called.
  34. ~SingleThreadTaskExecutor();
  35. const scoped_refptr<SingleThreadTaskRunner>& task_runner() const;
  36. MessagePumpType type() const { return type_; }
  37. // Sets the number of application tasks executed every time the MessagePump
  38. // asks its delegate to DoWork(). Defaults to 1. Can be increased in some
  39. // scenarios where the native pump (i.e. not MessagePumpType::DEFAULT) has
  40. // high overhead and yielding to native isn't critical.
  41. void SetWorkBatchSize(int work_batch_size);
  42. private:
  43. explicit SingleThreadTaskExecutor(MessagePumpType type,
  44. std::unique_ptr<MessagePump> pump);
  45. std::unique_ptr<sequence_manager::SequenceManager> sequence_manager_;
  46. scoped_refptr<sequence_manager::TaskQueue> default_task_queue_;
  47. MessagePumpType type_;
  48. SimpleTaskExecutor simple_task_executor_;
  49. };
  50. } // namespace base
  51. #endif // BASE_TASK_SINGLE_THREAD_TASK_EXECUTOR_H_