Skip to content

Instantly share code, notes, and snippets.

@ugovaretto
Created April 6, 2021 16:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ugovaretto/75e569efe942f8e60ea6f5affc0e2694 to your computer and use it in GitHub Desktop.
Save ugovaretto/75e569efe942f8e60ea6f5affc0e2694 to your computer and use it in GitHub Desktop.
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