跳至主要內容

56.C++线程控制_栅栏

约 303 字大约 1 分钟

std::barrier 是 C++20 引入的同步机制,用于让多个线程在特定点等待,直到所有线程都到达,然后一起继续执行。

基本使用

#include <iostream>
#include <thread>
#include <barrier>

const int NUM_THREADS = 3;
std::barrier sync_point(NUM_THREADS); // 3 个线程的栅栏

void worker(int id) {
    std::cout << "线程 " << id << " 开始阶段 1\n";
    std::this_thread::sleep_for(std::chrono::milliseconds(500 * id));  // 模拟工作

    sync_point.arrive_and_wait(); // 所有线程必须到这里才继续

    std::cout << "线程 " << id << " 进入阶段 2\n";
    std::this_thread::sleep_for(std::chrono::milliseconds(500 * id));  

    sync_point.arrive_and_wait(); // 再次同步

    std::cout << "线程 " << id << " 完成所有阶段\n";
}

int main() {
    std::thread threads[NUM_THREADS];
    for (int i = 0; i < NUM_THREADS; ++i)
        threads[i] = std::thread(worker, i + 1);

    for (auto& t : threads)
        t.join();

    return 0;
}

使用回调函数

#include <iostream>
#include <thread>
#include <barrier>

const int NUM_THREADS = 3;

// 栅栏 + 回调函数
std::barrier sync_point(NUM_THREADS, [] {
    std::cout << "所有线程完成阶段,执行回调函数...\n";
});

void worker(int id) {
    std::cout << "线程 " << id << " 开始工作\n";
    std::this_thread::sleep_for(std::chrono::milliseconds(500 * id));  

    sync_point.arrive_and_wait(); // 所有线程必须到达

    std::cout << "线程 " << id << " 进入下一阶段\n";
}

int main() {
    std::thread threads[NUM_THREADS];
    for (int i = 0; i < NUM_THREADS; ++i)
        threads[i] = std::thread(worker, i + 1);

    for (auto& t : threads)
        t.join();

    return 0;
}