diff --git a/muduo/base/Thread.cc b/muduo/base/Thread.cc index c8a052eeb..e8e581175 100644 --- a/muduo/base/Thread.cc +++ b/muduo/base/Thread.cc @@ -63,26 +63,25 @@ struct ThreadData typedef muduo::Thread::ThreadFunc ThreadFunc; ThreadFunc func_; string name_; - std::weak_ptr wkTid_; + pid_t* tid_; + CountDownLatch* latch_; ThreadData(ThreadFunc func, const string& name, - const std::shared_ptr& tid) + pid_t* tid, + CountDownLatch* latch) : func_(std::move(func)), name_(name), - wkTid_(tid) + tid_(tid), + latch_(latch) { } void runInThread() { - pid_t tid = muduo::CurrentThread::tid(); - - std::shared_ptr ptid = wkTid_.lock(); - if (ptid) - { - *ptid = tid; - ptid.reset(); - } + *tid_ = muduo::CurrentThread::tid(); + tid_ = NULL; + latch_->countDown(); + latch_ = NULL; muduo::CurrentThread::t_threadName = name_.empty() ? "muduoThread" : name_.c_str(); ::prctl(PR_SET_NAME, muduo::CurrentThread::t_threadName); @@ -156,9 +155,10 @@ Thread::Thread(ThreadFunc func, const string& n) : started_(false), joined_(false), pthreadId_(0), - tid_(new pid_t(0)), + tid_(0), func_(std::move(func)), - name_(n) + name_(n), + latch_(1) { setDefaultName(); } @@ -187,13 +187,18 @@ void Thread::start() assert(!started_); started_ = true; // FIXME: move(func_) - detail::ThreadData* data = new detail::ThreadData(func_, name_, tid_); + detail::ThreadData* data = new detail::ThreadData(func_, name_, &tid_, &latch_); if (pthread_create(&pthreadId_, NULL, &detail::startThread, data)) { started_ = false; delete data; // or no delete? LOG_SYSFATAL << "Failed in pthread_create"; } + else + { + latch_.wait(); + assert(tid_ > 0); + } } int Thread::join() diff --git a/muduo/base/Thread.h b/muduo/base/Thread.h index b5ac4dad6..36efd5e56 100644 --- a/muduo/base/Thread.h +++ b/muduo/base/Thread.h @@ -7,6 +7,7 @@ #define MUDUO_BASE_THREAD_H #include +#include #include #include @@ -30,7 +31,7 @@ class Thread : noncopyable bool started() const { return started_; } // pthread_t pthreadId() const { return pthreadId_; } - pid_t tid() const { return *tid_; } + pid_t tid() const { return tid_; } const string& name() const { return name_; } static int numCreated() { return numCreated_.get(); } @@ -41,9 +42,10 @@ class Thread : noncopyable bool started_; bool joined_; pthread_t pthreadId_; - std::shared_ptr tid_; + pid_t tid_; ThreadFunc func_; string name_; + CountDownLatch latch_; static AtomicInt32 numCreated_; }; diff --git a/muduo/base/tests/Thread_test.cc b/muduo/base/tests/Thread_test.cc index 2bbc10ab9..36c32b356 100644 --- a/muduo/base/tests/Thread_test.cc +++ b/muduo/base/tests/Thread_test.cc @@ -55,11 +55,13 @@ int main() muduo::Thread t1(threadFunc); t1.start(); + printf("t1.tid=%d\n", t1.tid()); t1.join(); muduo::Thread t2(std::bind(threadFunc2, 42), "thread for free function with argument"); t2.start(); + printf("t2.tid=%d\n", t2.tid()); t2.join(); Foo foo(87.53);