美文网首页
c++ 使用mutex cond 实现 Barrier

c++ 使用mutex cond 实现 Barrier

作者: 贼噶人 | 来源:发表于2020-01-22 11:12 被阅读0次
    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

    相关文章

      网友评论

          本文标题:c++ 使用mutex cond 实现 Barrier

          本文链接:https://www.haomeiwen.com/subject/bjiezctx.html