muduo库-线程同步CountDownLatch/Condition

muduo库-线程同步CountDownLatch/Condition

多线程同步中的问题

多线程环境中,常有这样一种同步情况:一个线程等待其他所有线程完成指定工作。比如,在开启一个新线程后,虽然已经启动线程函数,很可能还有一些准备工作需要完成(如更新当前线程id,名称等信息),这样,调用线程(创建线程的线程)并不能马上投入工作,立即向新线程传递数据,可能造成未定义行为,如调用线程的某段代码依赖于子线程id。

在muduo库中使用CountDownLatch类来解决这个问题。

Condition

Condition类图:

Condition类是muduo库中对系统线程条件变量类函数进行的封装;往往跟mutexlock配合使用,但也不控制其对象的生存期。

整个condition类主要为方便用户使用,封装pthread_cond_signal为notify(),封装pthread_cond_broadcastnotifyAll();封装pthread_cond_waitwait();封装pthread_cond_timedwaitwaitForSeconds();

CountDownLatch

CountDownLatch 也被称为门阀 、计数器 或者 闭锁。用于多个线程之间的同步,特别是一个线程等待另一个或多个线程。CountDownLatch类图如下:

CountDownLatch内部持有一个向下计数的计数器count_,构造时给定一个初值,代表需要等待的线程数。每个线程完成一个任务,count_减1,当count_值减到0时,代表所有线程已经完成了所有任务,在CountDownLatch上等待的线程就可以继续执行了。

CountDownLatch的接口

需要等待其他线程完成任务的线程,调用wait(),等待count_变为0;

任务线程,如果完成了任务,就调用countDown(),将count_计数值-1,值减到0时,会唤醒所有等待线程继续执行;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
* Count down from a count user specified to zero.
*
* Thread safe.
*/
class CountDownLatch
{
public:
explicit CountDownLatch(int count);

/**
* Wait until count_ decrease to 0
*/
void wait();
/**
* Decrease 1 in count_
*/
void countDown();

/**
* Return the value of count_
*/
int getCount() const;

private:
mutable MutexLock mutex_;
Condition cond_ GUARDED_BY(mutex_);
int count_ GUARDED_BY(mutex_);
};

CountDownLatch的实现

通过mutex_,确保所有对count_的操作,都是线程安全的。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
CountDownLatch::CountDownLatch(int count) : mutex_(), cond_(mutex_), count_(count)
{
}

void CountDownLatch::wait()
{
MutexLockGuard lock(mutex_);
while (count_ > 0)
{
cond_.wait();
}
}

/**
* Count down count_ from init value to 0, then notify thread
* waiting on the condition cond_.
*/
void CountDownLatch::countDown()
{
MutexLockGuard lock(mutex_);
--count_;
if (count_ == 0)
{
cond_.notifyAll();
}
}

int CountDownLatch::getCount() const {
MutexLockGuard lock(mutex_);
return count_;
}

参考:muduo笔记 线程同步CountDownLatch


muduo库-线程同步CountDownLatch/Condition
https://gstarmin.github.io/2023/06/26/muduo库-线程同步CountDownLatch-Condition/
作者
Starmin
发布于
2023年6月26日
许可协议