Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
C++ barrier
#include <chrono>
#include <condition_variable>
#include <iostream>
#include <thread>
class Barrier {
public:
Barrier(uint32_t count) : threadCount(count), counter(0), waiting(0) {}
void wait() {
std::unique_lock<std::mutex> lk(guard);
++counter;
++waiting;
condition.wait(lk, [&] { return counter == threadCount; });
condition.notify_all();
--waiting;
if (waiting == 0) {
counter = 0;
}
lk.unlock();
}
private:
std::mutex guard;
std::condition_variable condition;
uint32_t counter;
uint32_t threadCount;
uint32_t waiting;
};
Barrier barrier(4);
void fun1() {
std::this_thread::sleep_for(std::chrono::seconds(3));
barrier.wait();
std::cout << "fun1 awake\n" << std::endl;
}
void fun2() {
barrier.wait();
std::cout << "fun2 awake\n" << std::endl;
}
int main() {
std::thread t1(fun1);
std::thread t2(fun2);
std::thread t4(fun1);
std::thread t3(fun2);
t1.join();
t2.join();
t3.join();
t4.join();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment