#include "base/threading/thread.h"
#include <memory>
#include <type_traits>
#include <utility>
#include "base/dcheck_is_on.h"
#include "base/functional/bind.h"
#include "base/functional/callback_helpers.h"
#include "base/location.h"
#include "base/logging.h"
#include "base/memory/ptr_util.h"
#include "base/memory/scoped_refptr.h"
#include "base/message_loop/message_pump.h"
#include "base/run_loop.h"
#include "base/synchronization/waitable_event.h"
#include "base/task/current_thread.h"
#include "base/task/sequence_manager/sequence_manager_impl.h"
#include "base/task/sequence_manager/task_queue.h"
#include "base/task/single_thread_task_runner.h"
#include "base/threading/thread_id_name_manager.h"
#include "base/threading/thread_restrictions.h"
#include "base/types/pass_key.h"
#include "build/build_config.h"
#include "third_party/abseil-cpp/absl/base/dynamic_annotations.h"
#if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
#include <optional>
#include "base/files/file_descriptor_watcher_posix.h"
#endif
#if BUILDFLAG(IS_WIN)
#include "base/win/scoped_com_initializer.h"
#endif
namespace base {
#if DCHECK_IS_ON()
namespace {
constinit thread_local bool was_quit_properly = false;
}
#endif
namespace internal {
class SequenceManagerThreadDelegate : public Thread::Delegate {
public:
explicit SequenceManagerThreadDelegate(
MessagePumpType message_pump_type,
OnceCallback<std::unique_ptr<MessagePump>()> message_pump_factory,
std::unique_ptr<base::sequence_manager::SequenceManagerSettings>
sequence_manager_settings)
: sequence_manager_(
sequence_manager::internal::CreateUnboundSequenceManagerImpl(
PassKey<base::internal::SequenceManagerThreadDelegate>(),
sequence_manager_settings
? std::move(sequence_manager_settings->settings)
: sequence_manager::SequenceManager::Settings::Builder()
.SetMessagePumpType(message_pump_type)
.Build())),
default_task_queue_(sequence_manager_->CreateTaskQueue(
sequence_manager::TaskQueue::Spec(
sequence_manager::QueueName::DEFAULT_TQ))),
message_pump_factory_(std::move(message_pump_factory)) {
sequence_manager_->SetDefaultTaskRunner(default_task_queue_->task_runner());
}
~SequenceManagerThreadDelegate() override = default;
scoped_refptr<SingleThreadTaskRunner> GetDefaultTaskRunner() override {
return sequence_manager_->GetTaskRunner();
}
void BindToCurrentThread() override {
sequence_manager_->BindToMessagePump(
std::move(message_pump_factory_).Run());
}
void AddTaskObserver(TaskObserver* observer) override {
sequence_manager_->AddTaskObserver(observer);
}
private:
std::unique_ptr<sequence_manager::internal::SequenceManagerImpl>
sequence_manager_;
sequence_manager::TaskQueue::Handle default_task_queue_;
OnceCallback<std::unique_ptr<MessagePump>()> message_pump_factory_;
};
}
Thread::Options::Options() = default;
Thread::Options::Options(MessagePumpType type, size_t size)
: message_pump_type(type), stack_size(size) {}
Thread::Options::Options(ThreadType thread_type) : thread_type(thread_type) {}
Thread::Options::Options(Options&& other)
: message_pump_type(std::move(other.message_pump_type)),
delegate(std::move(other.delegate)),
message_pump_factory(std::move(other.message_pump_factory)),
stack_size(std::move(other.stack_size)),
thread_type(std::move(other.thread_type)),
joinable(std::move(other.joinable)),
sequence_manager_settings(std::move(other.sequence_manager_settings)),
task_observer(std::move(other.task_observer)) {
other.moved_from = true;
}
Thread::Options& Thread::Options::operator=(Thread::Options&& other) {
DCHECK_NE(this, &other);
message_pump_type = std::move(other.message_pump_type);
delegate = std::move(other.delegate);
message_pump_factory = std::move(other.message_pump_factory);
stack_size = std::move(other.stack_size);
thread_type = std::move(other.thread_type);
joinable = std::move(other.joinable);
task_observer = std::move(other.task_observer);
other.moved_from = true;
return *this;
}
Thread::Options::~Options() = default;
Thread::Thread(const std::string& name)
: id_event_(WaitableEvent::ResetPolicy::MANUAL,
WaitableEvent::InitialState::NOT_SIGNALED),
name_(name),
start_event_(WaitableEvent::ResetPolicy::MANUAL,
WaitableEvent::InitialState::NOT_SIGNALED) {
owning_sequence_checker_.DetachFromSequence();
}
Thread::~Thread() {
Stop();
}
bool Thread::Start() {
DCHECK(owning_sequence_checker_.CalledOnValidSequence());
Options options;
#if BUILDFLAG(IS_WIN)
if (com_status_ == STA) {
options.message_pump_type = MessagePumpType::UI;
}
#endif
return StartWithOptions(std::move(options));
}
bool Thread::StartWithOptions(Options options) {
DCHECK(options.IsValid());
DCHECK(owning_sequence_checker_.CalledOnValidSequence());
DCHECK(!delegate_);
DCHECK(!IsRunning());
DCHECK(!stopping_) << "Starting a non-joinable thread a second time? That's "
<< "not allowed!";
#if BUILDFLAG(IS_WIN)
DCHECK((com_status_ != STA) ||
(options.message_pump_type == MessagePumpType::UI));
#endif
id_event_.Reset();
id_ = kInvalidThreadId;
#if BUILDFLAG(IS_ARKWEB)
real_id_ = kInvalidThreadId;
#endif
SetThreadWasQuitProperly(false);
if (options.delegate) {
DCHECK(!options.message_pump_factory);
delegate_ = std::move(options.delegate);
} else if (options.message_pump_factory) {
delegate_ = std::make_unique<internal::SequenceManagerThreadDelegate>(
MessagePumpType::CUSTOM, options.message_pump_factory,
std::move(options.sequence_manager_settings));
} else {
delegate_ = std::make_unique<internal::SequenceManagerThreadDelegate>(
options.message_pump_type,
BindOnce([](MessagePumpType type) { return MessagePump::Create(type); },
options.message_pump_type),
std::move(options.sequence_manager_settings));
}
if (options.task_observer) {
delegate_->AddTaskObserver(options.task_observer);
}
start_event_.Reset();
{
AutoLock lock(thread_lock_);
bool success = options.joinable
? PlatformThread::CreateWithType(
options.stack_size, this, &thread_,
options.thread_type, options.message_pump_type)
: PlatformThread::CreateNonJoinableWithType(
options.stack_size, this, options.thread_type,
options.message_pump_type);
if (!success) {
DLOG(ERROR) << "failed to create thread";
return false;
}
}
joinable_ = options.joinable;
return true;
}
bool Thread::StartAndWaitForTesting() {
DCHECK(owning_sequence_checker_.CalledOnValidSequence());
bool result = Start();
if (!result) {
return false;
}
WaitUntilThreadStarted();
return true;
}
bool Thread::WaitUntilThreadStarted() const {
DCHECK(owning_sequence_checker_.CalledOnValidSequence());
if (!delegate_) {
return false;
}
base::ScopedAllowBaseSyncPrimitivesOutsideBlockingScope allow_wait;
start_event_.Wait();
return true;
}
void Thread::FlushForTesting() {
DCHECK(owning_sequence_checker_.CalledOnValidSequence());
if (!delegate_) {
return;
}
WaitableEvent done(WaitableEvent::ResetPolicy::AUTOMATIC,
WaitableEvent::InitialState::NOT_SIGNALED);
task_runner()->PostTask(FROM_HERE,
BindOnce(&WaitableEvent::Signal, Unretained(&done)));
done.Wait();
}
void Thread::Stop() {
DCHECK(joinable_);
AutoLock lock(thread_lock_);
StopSoon();
if (thread_.is_null()) {
return;
}
PlatformThread::Join(thread_);
thread_ = base::PlatformThreadHandle();
DCHECK(!delegate_);
stopping_ = false;
}
void Thread::StopSoon() {
if (stopping_ || !delegate_) {
return;
}
stopping_ = true;
task_runner()->PostTask(
FROM_HERE, base::BindOnce(&Thread::ThreadQuitHelper, Unretained(this)));
}
void Thread::DetachFromSequence() {
DCHECK(owning_sequence_checker_.CalledOnValidSequence());
owning_sequence_checker_.DetachFromSequence();
}
PlatformThreadId Thread::GetThreadId() const {
if (!id_event_.IsSignaled()) {
base::ScopedAllowBaseSyncPrimitivesOutsideBlockingScope allow_wait;
id_event_.Wait();
}
return id_;
}
#if BUILDFLAG(IS_ARKWEB)
PlatformThreadId Thread::GetThreadRealId() const {
if (!id_event_.IsSignaled()) {
base::ScopedAllowBaseSyncPrimitivesOutsideBlockingScope allow_wait;
id_event_.Wait();
}
return real_id_;
}
#endif
bool Thread::IsRunning() const {
if (delegate_ && !stopping_) {
return true;
}
AutoLock lock(running_lock_);
return running_;
}
void Thread::Run(RunLoop* run_loop) {
DCHECK(id_event_.IsSignaled());
DCHECK_EQ(id_, PlatformThread::CurrentId());
run_loop->Run();
}
void Thread::SetThreadWasQuitProperly(bool flag) {
#if DCHECK_IS_ON()
was_quit_properly = flag;
#endif
}
bool Thread::GetThreadWasQuitProperly() {
#if DCHECK_IS_ON()
return was_quit_properly;
#else
return true;
#endif
}
void Thread::ThreadMain() {
PlatformThread::SetName(name_.c_str());
ABSL_ANNOTATE_THREAD_NAME(name_.c_str());
DCHECK(!id_event_.IsSignaled());
DCHECK_EQ(kInvalidThreadId, id_);
id_ = PlatformThread::CurrentId();
#if BUILDFLAG(IS_ARKWEB)
real_id_ = PlatformThread::CurrentRealId();
#endif
DCHECK_NE(kInvalidThreadId, id_);
id_event_.Signal();
DCHECK(delegate_);
delegate_->BindToCurrentThread();
DCHECK(CurrentThread::Get());
DCHECK(SingleThreadTaskRunner::HasCurrentDefault());
#if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
std::unique_ptr<FileDescriptorWatcher> file_descriptor_watcher;
if (CurrentIOThread::IsSet()) {
file_descriptor_watcher = std::make_unique<FileDescriptorWatcher>(
delegate_->GetDefaultTaskRunner());
}
#endif
#if BUILDFLAG(IS_WIN)
std::unique_ptr<win::ScopedCOMInitializer> com_initializer;
if (com_status_ != NONE) {
com_initializer.reset(
(com_status_ == STA)
? new win::ScopedCOMInitializer()
: new win::ScopedCOMInitializer(win::ScopedCOMInitializer::kMTA));
}
#endif
Init();
{
AutoLock lock(running_lock_);
running_ = true;
}
start_event_.Signal();
RunLoop run_loop;
run_loop_ = &run_loop;
Run(run_loop_);
{
AutoLock lock(running_lock_);
running_ = false;
}
CleanUp();
#if BUILDFLAG(IS_WIN)
com_initializer.reset();
#endif
DCHECK(GetThreadWasQuitProperly());
delegate_.reset();
run_loop_ = nullptr;
}
void Thread::ThreadQuitHelper() {
DCHECK(run_loop_);
run_loop_->QuitWhenIdle();
SetThreadWasQuitProperly(true);
}
}