#include <thread>
#include <mutex>
#include <condition_variable>
#include <iostream>
using namespace std;

class barrier {
public:
    barrier(int n): teller(n) {
    }
    void wait() {
        unique_lock<mutex> lock(m);
        --teller;
        while (teller > 0) {
            c.wait(lock);
        }
        c.notify_one();
    }
private:
    int teller;
    mutex m;
    condition_variable c;
};

barrier b(3);
mutex m;

void task(int delay) {
    thread::id id(this_thread::get_id());
    {
        lock_guard<mutex> g(m);
        cout << "Thread " << id << " gestart" << endl;
    }
    this_thread::sleep_for(chrono::seconds(delay));
    {
        lock_guard<mutex> g(m);
        cout << "Thread " << id << " wordt wakker" << endl;
    }
    b.wait();
    {
        lock_guard<mutex> g(m);
        cout << "Thread " << id << " passeert barrier" << endl;
    }
}

int main() {
    thread t1(&task, 1), t2(&task, 2), t3(&task, 3);
    t1.join(); t2.join(); t3.join();
    cin.get();
    return 0; 
}
