class Barrier{
private:
uv_mutex_t mutex;
uv_cond_t cond;
int number;
public:
Barrier(int number){
this->number = number;
uv_cond_init(&cond);
uv_mutex_init(&mutex);
}
void wait(){
uv_mutex_lock(&mutex);
--number;
if(number > 0){
uv_cond_wait(&cond, &mutex);
}
else{
uv_cond_broadcast(&cond);
}
uv_mutex_unlock(&mutex);
}
~Barrier(){
std::cout << "~Barrier" << std::endl;
uv_mutex_destroy(&mutex);
uv_cond_destroy(&cond);
}
};
int main(const int argc, const char * argv[]) {
Barrier barrier(5);
uv_thread_t tids[5];
for(int i = 0;i < 4;i++){
uv_thread_create(&tids[i], [](void *data){
Barrier* const barrier = (Barrier *)data;
barrier->wait();
std::cout << "Thread done!" << std::endl;
}, &barrier);
}
std::cout << "main thread wait!" << std::endl;
for(int i = 0; i < INT_MAX >> 1;++i){
}
std::cout << "main thread wait done!" << std::endl;
barrier.wait();
for(int i = 0; i < INT_MAX >> 1;++i){
}
std::cout << "done!" << std::endl;
}
运行输出
main thread wait!
main thread wait done!
Thread done!
Thread done!
Thread done!
Thread done!
done!
~Barrier
Program ended with exit code: 0
网友评论