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