diff options
Diffstat (limited to 'base/threading/thread.h')
-rw-r--r-- | base/threading/thread.h | 141 |
1 files changed, 110 insertions, 31 deletions
diff --git a/base/threading/thread.h b/base/threading/thread.h index c9a77d7323..01f7d8e250 100644 --- a/base/threading/thread.h +++ b/base/threading/thread.h @@ -15,7 +15,9 @@ #include "base/macros.h" #include "base/message_loop/message_loop.h" #include "base/message_loop/timer_slack.h" +#include "base/sequence_checker.h" #include "base/single_thread_task_runner.h" +#include "base/synchronization/atomic_flag.h" #include "base/synchronization/lock.h" #include "base/synchronization/waitable_event.h" #include "base/threading/platform_thread.h" @@ -24,6 +26,7 @@ namespace base { class MessagePump; +class RunLoop; // A simple thread abstraction that establishes a MessageLoop on a new thread. // The consumer uses the MessageLoop of the thread to cause code to execute on @@ -38,6 +41,18 @@ class MessagePump; // (1) Thread::CleanUp() // (2) MessageLoop::~MessageLoop // (3.b) MessageLoop::DestructionObserver::WillDestroyCurrentMessageLoop +// +// This API is not thread-safe: unless indicated otherwise its methods are only +// valid from the owning sequence (which is the one from which Start() is +// invoked -- should it differ from the one on which it was constructed). +// +// Sometimes it's useful to kick things off on the initial sequence (e.g. +// construction, Start(), task_runner()), but to then hand the Thread over to a +// pool of users for the last one of them to destroy it when done. For that use +// case, Thread::DetachFromSequence() allows the owning sequence to give up +// ownership. The caller is then responsible to ensure a happens-after +// relationship between the DetachFromSequence() call and the next use of that +// Thread object (including ~Thread()). class BASE_EXPORT Thread : PlatformThread::Delegate { public: struct BASE_EXPORT Options { @@ -50,10 +65,10 @@ class BASE_EXPORT Thread : PlatformThread::Delegate { // Specifies the type of message loop that will be allocated on the thread. // This is ignored if message_pump_factory.is_null() is false. - MessageLoop::Type message_loop_type; + MessageLoop::Type message_loop_type = MessageLoop::TYPE_DEFAULT; // Specifies timer slack for thread message loop. - TimerSlack timer_slack; + TimerSlack timer_slack = TIMER_SLACK_NONE; // Used to create the MessagePump for the MessageLoop. The callback is Run() // on the thread. If message_pump_factory.is_null(), then a MessagePump @@ -64,10 +79,18 @@ class BASE_EXPORT Thread : PlatformThread::Delegate { // Specifies the maximum stack size that the thread is allowed to use. // This does not necessarily correspond to the thread's initial stack size. // A value of 0 indicates that the default maximum should be used. - size_t stack_size; + size_t stack_size = 0; // Specifies the initial thread priority. - ThreadPriority priority; + ThreadPriority priority = ThreadPriority::NORMAL; + + // If false, the thread will not be joined on destruction. This is intended + // for threads that want TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN + // semantics. Non-joinable threads can't be joined (must be leaked and + // can't be destroyed or Stop()'ed). + // TODO(gab): allow non-joinable instances to be deleted without causing + // user-after-frees (proposal @ https://crbug.com/629139#c14) + bool joinable = true; }; // Constructor. @@ -125,12 +148,19 @@ class BASE_EXPORT Thread : PlatformThread::Delegate { // carefully for production code. bool WaitUntilThreadStarted() const; - // Signals the thread to exit and returns once the thread has exited. After - // this method returns, the Thread object is completely reset and may be used - // as if it were newly constructed (i.e., Start may be called again). + // Blocks until all tasks previously posted to this thread have been executed. + void FlushForTesting(); + + // Signals the thread to exit and returns once the thread has exited. The + // Thread object is completely reset and may be used as if it were newly + // constructed (i.e., Start may be called again). Can only be called if + // |joinable_|. // // Stop may be called multiple times and is simply ignored if the thread is - // already stopped. + // already stopped or currently stopping. + // + // Start/Stop are not thread-safe and callers that desire to invoke them from + // different threads must ensure mutual exclusion. // // NOTE: If you are a consumer of Thread, it is not necessary to call this // before deleting your Thread objects, as the destructor will do it. @@ -145,11 +175,17 @@ class BASE_EXPORT Thread : PlatformThread::Delegate { // deadlock on Windows with printer worker thread. In any other case, Stop() // should be used. // - // StopSoon should not be called multiple times as it is risky to do so. It - // could cause a timing issue in message_loop() access. Call Stop() to reset - // the thread object once it is known that the thread has quit. + // Call Stop() to reset the thread object once it is known that the thread has + // quit. void StopSoon(); + // Detaches the owning sequence, indicating that the next call to this API + // (including ~Thread()) can happen from a different sequence (to which it + // will be rebound). This call itself must happen on the current owning + // sequence and the caller must ensure the next API call has a happens-after + // relationship with this one. + void DetachFromSequence(); + // Returns the message loop for this thread. Use the MessageLoop's // PostTask methods to execute code on the thread. This only returns // non-null after a successful call to Start. After Stop has been called, @@ -158,29 +194,52 @@ class BASE_EXPORT Thread : PlatformThread::Delegate { // NOTE: You must not call this MessageLoop's Quit method directly. Use // the Thread's Stop method instead. // - MessageLoop* message_loop() const { return message_loop_; } + // In addition to this Thread's owning sequence, this can also safely be + // called from the underlying thread itself. + MessageLoop* message_loop() const { + // This class doesn't provide synchronization around |message_loop_| and as + // such only the owner should access it (and the underlying thread which + // never sees it before it's set). In practice, many callers are coming from + // unrelated threads but provide their own implicit (e.g. memory barriers + // from task posting) or explicit (e.g. locks) synchronization making the + // access of |message_loop_| safe... Changing all of those callers is + // unfeasible; instead verify that they can reliably see + // |message_loop_ != nullptr| without synchronization as a proof that their + // external synchronization catches the unsynchronized effects of Start(). + // TODO(gab): Despite all of the above this test has to be disabled for now + // per crbug.com/629139#c6. + // DCHECK(owning_sequence_checker_.CalledOnValidSequence() || + // (id_event_.IsSignaled() && id_ == PlatformThread::CurrentId()) || + // message_loop_); + return message_loop_; + } // Returns a TaskRunner for this thread. Use the TaskRunner's PostTask // methods to execute code on the thread. Returns nullptr if the thread is not // running (e.g. before Start or after Stop have been called). Callers can // hold on to this even after the thread is gone; in this situation, attempts // to PostTask() will fail. + // + // In addition to this Thread's owning sequence, this can also safely be + // called from the underlying thread itself. scoped_refptr<SingleThreadTaskRunner> task_runner() const { + // Refer to the DCHECK and comment inside |message_loop()|. + DCHECK(owning_sequence_checker_.CalledOnValidSequence() || + (id_event_.IsSignaled() && id_ == PlatformThread::CurrentId()) || + message_loop_); return message_loop_ ? message_loop_->task_runner() : nullptr; } // Returns the name of this thread (for display in debugger too). const std::string& thread_name() const { return name_; } - // The native thread handle. - PlatformThreadHandle thread_handle() { return thread_; } - // Returns the thread ID. Should not be called before the first Start*() // call. Keeps on returning the same ID even after a Stop() call. The next // Start*() call renews the ID. // // WARNING: This function will block if the thread hasn't started yet. // + // This method is thread-safe. PlatformThreadId GetThreadId() const; // Returns true if the thread has been started, and not yet stopped. @@ -190,8 +249,8 @@ class BASE_EXPORT Thread : PlatformThread::Delegate { // Called just prior to starting the message loop virtual void Init() {} - // Called to start the message loop - virtual void Run(MessageLoop* message_loop); + // Called to start the run loop + virtual void Run(RunLoop* run_loop); // Called just after the message loop ends virtual void CleanUp() {} @@ -199,8 +258,11 @@ class BASE_EXPORT Thread : PlatformThread::Delegate { static void SetThreadWasQuitProperly(bool flag); static bool GetThreadWasQuitProperly(); - void set_message_loop(MessageLoop* message_loop) { - message_loop_ = message_loop; + // Bind this Thread to an existing MessageLoop instead of starting a new one. + void SetMessageLoop(MessageLoop* message_loop); + + bool using_external_message_loop() const { + return using_external_message_loop_; } private: @@ -215,19 +277,25 @@ class BASE_EXPORT Thread : PlatformThread::Delegate { // PlatformThread::Delegate methods: void ThreadMain() override; + void ThreadQuitHelper(); + #if defined(OS_WIN) // Whether this thread needs to initialize COM, and if so, in what mode. - ComStatus com_status_; + ComStatus com_status_ = NONE; #endif + // Mirrors the Options::joinable field used to start this thread. Verified + // on Stop() -- non-joinable threads can't be joined (must be leaked). + bool joinable_ = true; + // If true, we're in the middle of stopping, and shouldn't access // |message_loop_|. It may non-nullptr and invalid. // Should be written on the thread that created this thread. Also read data // could be wrong on other threads. - bool stopping_; + bool stopping_ = false; // True while inside of Run(). - bool running_; + bool running_ = false; mutable base::Lock running_lock_; // Protects |running_|. // The thread's handle. @@ -235,24 +303,35 @@ class BASE_EXPORT Thread : PlatformThread::Delegate { mutable base::Lock thread_lock_; // Protects |thread_|. // The thread's id once it has started. - PlatformThreadId id_; - mutable WaitableEvent id_event_; // Protects |id_|. - - // The thread's message loop. Valid only while the thread is alive. Set - // by the created thread. - MessageLoop* message_loop_; + PlatformThreadId id_ = kInvalidThreadId; + // Protects |id_| which must only be read while it's signaled. + mutable WaitableEvent id_event_; + + // The thread's MessageLoop and RunLoop. Valid only while the thread is alive. + // Set by the created thread. + MessageLoop* message_loop_ = nullptr; + RunLoop* run_loop_ = nullptr; + + // True only if |message_loop_| was externally provided by |SetMessageLoop()| + // in which case this Thread has no underlying |thread_| and should merely + // drop |message_loop_| on Stop(). In that event, this remains true after + // Stop() was invoked so that subclasses can use this state to build their own + // cleanup logic as required. + bool using_external_message_loop_ = false; // Stores Options::timer_slack_ until the message loop has been bound to // a thread. - TimerSlack message_loop_timer_slack_; + TimerSlack message_loop_timer_slack_ = TIMER_SLACK_NONE; // The name of the thread. Used for debugging purposes. - std::string name_; + const std::string name_; // Signaled when the created thread gets ready to use the message loop. mutable WaitableEvent start_event_; - friend void ThreadQuitHelper(); + // This class is not thread-safe, use this to verify access from the owning + // sequence of the Thread. + SequenceChecker owning_sequence_checker_; DISALLOW_COPY_AND_ASSIGN(Thread); }; |