[C++] latch
Updated:
개요
- 스레드를 동기화 하는데 사용하는 하향 카운터
- 카운터 값은 생성 시 초기화
- 카운터가 0으로 감소할 때까지 차단
- barrier와 달리 재사용 불가
- 소멸자를 제외한 멤버 함수를 동시 호출해도 데이터 경합 없음
- 멤버 함수
- count_down()
- non-blocking 방식으로 카운터를 감소
- try_wait()
- 카운터가 0인지 확인
- wait()
- 카운터가 0이 될 때까지 차단
- arrive_and_wait()
- 카운터를 감소시키고 0이 될 때까지 차단
- max()
- 카운터의 최대값
- count_down()
예제
- 코드
#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