[C++] barrier
Updated:
개요
- 알려진 크기의 스레드 그룹이 barrier에 도달할때까지 차단하는 스레드 조정 메커니즘 제공
- 소멸자를 제외한 멤버 함수를 동시 호출해도 데이터 경합 없음
- latch와의 차이점
- 재사용 가능
- 스레드 그룹이 차단 해제된 경우
- 카운트는 생성 시 설정된 값에서 arrive_and_drop 호출 수를 뺀 값으로 재설정
- 차단 해제전에 callable 실행
- 재사용 가능
- 멤버 함수
- arrive()
- barrier에 도달하고 카운트 감소
- wait()
- callable이 실행될 때까지 차단
- arrive_and_wait()
- barrier에 도달하고 카운트 감소 후 차단
- arrive_and_drop()
- barrier에 도달하고 설정 카운트와 현재 카운트를 감소
- max()
- 카운트의 최대값
- arrive()
예제
- 코드
#include <barrier> #include <future> #include <iostream> #include <string> #include <vector> using namespace std; int main() { vector<string> datas = {"a", "b", "c"}; barrier done(ssize(datas), []() { static string s = "done1\n"; cout << s; s = "done2\n"; }); auto run = [&done](string s) { cout << s + " start" << endl; done.arrive_and_wait(); cout << s + " end" << endl; done.arrive_and_wait(); }; 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 done1 c end a end b end done2