@@ -147,6 +147,84 @@ Worker#2 3
147147Main 3
148148```
149149
150+ ## 完了関数を持つBarrierの例
151+ ``` cpp example
152+ #include < barrier>
153+ #include < iostream>
154+ #include < mutex>
155+ #include < string>
156+ #include < thread>
157+ #include < vector>
158+ #include < functional> // for std::ref
159+
160+ // 各フェーズ完了時に呼び出される完了関数
161+ struct PhaseNotifier {
162+ void operator()() const noexcept {
163+ std::lock_guard lk{cout_mtx};
164+ std::cout << "Phase " << current_phase << " completed!" << std::endl;
165+ current_phase++;
166+ }
167+
168+ static inline std::mutex cout_mtx;
169+ static inline int current_phase = 1;
170+ };
171+
172+ void worker_task(int id, std::barrier<PhaseNotifier >& sync, int phases) {
173+ for (int phase = 1; phase <= phases; phase++) {
174+ // 各ワーカーがフェーズの作業を実行
175+ {
176+ std::lock_guard lk{PhaseNotifier::cout_mtx};
177+ std::cout << "Worker " << id << " executing phase " << phase << std::endl;
178+ }
179+
180+ // フェーズ完了を通知して次のフェーズまで待機
181+ // 最後のスレッドが到達すると完了関数が呼び出される
182+ sync.arrive_and_wait();
183+ }
184+ }
185+
186+ int main() {
187+ constexpr int num_threads = 3;
188+ constexpr int num_phases = 3;
189+
190+ // 完了通知関数を持つバリア
191+ std::barrier sync{num_threads, PhaseNotifier{}};
192+
193+ std::vector< std::thread > threads;
194+
195+ // スレッド起動
196+ for (int i = 1; i <= num_threads; i++) {
197+ threads.emplace_back(worker_task, i, std::ref(sync), num_phases);
198+ }
199+
200+ // 全スレッドの終了を待機
201+ for (auto& t : threads) {
202+ t.join();
203+ }
204+
205+ return 0;
206+ }
207+ ```
208+ * std::barrier[color ff0000]
209+ * std::ref[link /reference/functional/ref.md]
210+ * arrive_and_wait()[link barrier/arrive_and_wait.md]
211+ * emplace_back[link /reference/vector/vector/emplace_back.md]
212+
213+ ### 出力例
214+ ```
215+ Worker 1 executing phase 1
216+ Worker 2 executing phase 1
217+ Worker 3 executing phase 1
218+ Phase 1 completed!
219+ Worker 3 executing phase 2
220+ Worker 2 executing phase 2
221+ Worker 1 executing phase 2
222+ Phase 2 completed!
223+ Worker 1 executing phase 3
224+ Worker 2 executing phase 3
225+ Worker 3 executing phase 3
226+ Phase 3 completed!
227+ ```
150228
151229## バージョン
152230### 言語
0 commit comments