Skip to content

Instantly share code, notes, and snippets.

@ayushgun
Last active August 20, 2023 15:11
Show Gist options
  • Save ayushgun/f988abf34598f8138b27aece22abd5da to your computer and use it in GitHub Desktop.
Save ayushgun/f988abf34598f8138b27aece22abd5da to your computer and use it in GitHub Desktop.
Example of multithreaded loop synchronization using std::barrier.
#include <barrier>
#include <functional>
#include <iostream>
#include <string>
#include <thread>
#include <vector>
struct Person {
std::string name;
int age;
Person(const std::string& name, int age) : name(name), age(age) {}
};
void task(std::barrier<std::function<void()>>& barrier,
const std::vector<Person>& data) {
for (const auto& person : data) {
std::cout << std::this_thread::get_id() << ": " << person.name << std::endl;
barrier.arrive_and_wait(); // The barrier synchronizes processing
}
}
// Completion function that runs on one of the threads each time all threads
// have arrived at the barrier
void finished() { std::cout << "Processed a chunk\n"; }
int main() {
std::barrier<std::function<void()>> barrier(
2, finished); // 2 threads will be spawned
std::vector<Person> chunks = {Person("John", 18), Person("Bob", 20),
Person("Ayush", 19)};
std::thread t1(task, std::ref(barrier), std::ref(chunks));
std::thread t2(task, std::ref(barrier), std::ref(chunks));
t1.join();
t2.join();
std::cout << "Processing of data chunks complete...\n";
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment