Skip to content

Thread里面的CountDownLatch的作用是什么? #610

Answered by chenshuo
yinghaoyu asked this question in Q&A
Discussion options

You must be logged in to vote

https://www.zhihu.com/question/294270506/answer/489820748

为了保证 Thread::start() 之后 Thread::tid() 立刻能拿到正确的值。
如果没有 latch_,会有 race condition,即调用 Thread::tid() 的时候线程还没有启动,结果返回初值 0。

struct ThreadData
{
  void runInThread()
  {
    *tid_ = muduo::CurrentThread::tid();
    tid_ = NULL;
    latch_->countDown();
    latch_ = NULL;

使用方法:

map<pid_t, unique_ptr<Thread>> threads;
Thread* thr = new Thread(...);
thr->start();
threads[thr->tid()].reset(thr);

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@yinghaoyu
Comment options

Answer selected by yinghaoyu
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants