Last active
June 8, 2018 15:34
-
-
Save louismanson/34ea9e46fc2f4fbfd9201adcfcfb5ede to your computer and use it in GitHub Desktop.
barrier for threads
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//============================================================================ | |
// Name : barrera.cpp | |
// Author : Luis Hernandez | |
// Version : 1 | |
// Copyright : CodeLouis | |
// Description : barier for threads | |
//============================================================================ | |
//g++ 5.4.0 | |
#include <iostream> | |
#include <thread> | |
#include <condition_variable> | |
#include <mutex> | |
using namespace std; | |
class Barrier{ | |
private: | |
std::mutex bmutex; | |
std::condition_variable cv; | |
std::size_t count; | |
std::size_t n; | |
std::size_t generation; | |
public: | |
explicit Barrier(unsigned sz =0):count{sz},n{sz},generation(0){}; | |
void wait(void){ | |
std::unique_lock<std::mutex> lck{bmutex}; | |
auto gen = generation; | |
if(n-- ==0) | |
{ | |
n = count; | |
generation++; | |
std::cout<<"generation "<< gen << endl; | |
cv.notify_all(); | |
} else{ | |
std::cout << "waiting... task " << n+1 <<endl; | |
cv.wait(lck,[this,gen]{return gen!= generation;}); | |
std::cout << "waiting... completed " << generation << endl; | |
} | |
} | |
}; | |
int main(){ | |
int numberThreads = 30; | |
int barrierLimit = 3; | |
numberThreads++; | |
std::thread mThreads[numberThreads]; | |
Barrier * mBarrier = new Barrier(barrierLimit); | |
for(int i=0; i<numberThreads; i++){ | |
mThreads[i] = std::thread(&Barrier::wait,mBarrier); | |
} | |
for(int i=0; i<numberThreads; i++){ | |
mThreads[i].join(); | |
} | |
std::cout << "End of threads" << endl; | |
delete mBarrier; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment