개요
- 스레드를 동기화 하는데 사용하는 하향 카운터
- 카운터 값은 생성 시 초기화
- 카운터가 0으로 감소할 때까지 차단
- barrier와 달리 재사용 불가
- 소멸자를 제외한 멤버 함수를 동시 호출해도 데이터 경합 없음
- 멤버 함수
- count_down()
- non-blocking 방식으로 카운터를 감소
- try_wait()
- wait()
- arrive_and_wait()
- max()
예제
- 코드
#include <future>
#include <iostream>
#include <latch>
#include <string>
#include <vector>
using namespace std;
int main() {
vector<string> datas = {"a", "b", "c"};
latch done(datas.size());
auto run = [&done](string s) {
cout << s + " start" << endl;
done.arrive_and_wait();
cout << s + " end" << endl;
};
vector<future<void>> futures;
for (const auto &iter : datas) {
futures.push_back(async(
launch::async, [run](string s) { run(s); }, iter));
}
for (auto &iter : futures) {
iter.get();
}
return 0;
}
- 실행 결과
a start
b start
c start
c end
a end
b end