bool Thread::StartWithOptions(const Options& options) { DCHECK(!message_loop_); SetThreadWasQuitProperly(false); StartupData startup_data(options); startup_data_ = &startup_data; if(!Create(options.stack_size, this, &thread_)) { DLOG(ERROR) << "failed to create thread"; startup_data_ = NULL; return false; } // 等待线程启动并初始化message_loop_. startup_data.event.Wait(); // 设置成NULL, 所以我们不会保存一个栈上对象的指针. startup_data_ = NULL; started_ = true; DCHECK(message_loop_); return true; }
void FrameworkThread::Run() { #ifndef NDEBUG #if defined(OS_WIN) && defined(COMPILER_MSVC) SetThreadName(GetCurrentThreadId(), name_.c_str()); #endif #endif InitTlsData(this); SetThreadWasQuitProperly(false); { ThreadId thread_id = Thread::CurrentId(); set_thread_id(thread_id); // The message loop for this thread. MessageLoop *message_loop; if (loop_type_ == MessageLoop::kCustomMessageLoop) message_loop = factory_->CreateMessageLoop(); else { if (loop_type_ == MessageLoop::kIOMessageLoop) message_loop = new IOMessageLoop; #if defined(OS_WIN) else if (loop_type_ == MessageLoop::kUIMessageLoop) message_loop = new UIMessageLoop; #endif else message_loop = new MessageLoop; } message_loop_ = message_loop; // Let the thread do extra initialization. // Let's do this before signaling we are started. Init(); event_.Signal(); #if defined(OS_WIN) message_loop_->RunWithDispatcher(dispatcher_); #else message_loop_->Run(); #endif // OS_WIN // Let the thread do extra cleanup. Cleanup(); //DCHECK(GetThreadWasQuitProperly()); // We can't receive messages anymore. if (loop_type_ != MessageLoop::kCustomMessageLoop) delete message_loop_; else { delete message_loop_; factory_.reset(); } message_loop_ = NULL; } set_thread_id(kInvalidThreadId); { FrameworkThreadTlsData *tls = GetTlsData(); if (tls != NULL) { } //DCHECK(tls->managed == 0); // you must call ThreadManager::UnregisterThread before come there } FreeTlsData(); }
void FrameworkThread::DoStopSoon() { MessageLoop::current()->Quit(); SetThreadWasQuitProperly(true); }