c++ posix线程库CountDown封装和使用

本文介绍了C++中基于Posix线程库的CountDownLatch实现,它作为线程同步工具,主要用于主线程等待多个子线程完成任务或子线程等待主线程的通知。文中详细讲解了CountDownLatch的封装方法和使用示例,并提供了一个简单的测试案例,参考自muduo多线程编程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

CountDownLatch

CountDownLatch(倒计时器)是一种高层的线程间同步组件,主要有两个用途:

  • 主线程发起多个子线程,等待这些子线程都完成一定的任务后,主线程才继续执行。通常用于主线程等待多个子线程完成初始化。
  • 主线程发起多个子线程,子线程都等待主线程,主线程完成一些任务后通知子线程开始执行。通常用于多个子线程等待主线程发出起跑命令。
    当然可以直接用条件变量完成上述功能,不过使用CountDownLatch的话程序逻辑会更清晰。

封装

#ifndef _COUNTDOWNLATCH_H
#define _COUNTDOWNLATCH_H

#include "MutexLock.h"
#include "Condition.h"

class CountDownLatch : noncopyable{
public:
    CountDownLatch(int);
    ~CountDownLatch() = default;

    void wait();
    void countDown();
    int getCount() const;

private:
    int count_;
    mutable MutexLock mutex_;  //getCount中mutex状态会有修改,因此加mutable关键字
    Condition cond_;
};

#endif // _COUNTDOWNLATCH_H

#include "CountDownLatch.h"
#include "MutexLock.h"
#include "Condition.h"

CountDownLatch::CountDownLatch(int num):count_(num),mutex_(),cond_(mutex_){ }

void CountDownLatch::wait(){
    MutexLockGuard lock(mutex_);
    while(count_ > 0){
        cond_.wait();
    }
}

void CountDownLatch::countDown(){
    MutexLockGuard lock(mutex_);
    --count_;
    if(count_==0)
        cond_.notify();
}

int CountDownLatch::getCount() const{
    MutexLockGuard lock(mutex_);
    return count_;
}

使用

使用起来也是非常方便,用下面简单例子测试一下:

#include <iostream>
#include "MutexLock.h"
#include <pthread.h>
#include <cstdlib>
#include <unistd.h>
#include <sys/syscall.h>
#include "Condition.h"
#include "CountDownLatch.h"
#include "Thread2.h"

using namespace std;


pid_t gettid(){
    return syscall(__NR_gettid);
}

CountDownLatch latch(5);

void fun1(){
    while(1){
       cout<<"t1"<<endl;
       latch.countDown();
       sleep(rand()%2);
    }
}

void fun2(){
    while(1){
       cout<<"t2"<<endl;
       latch.countDown();
       sleep(rand()%2);
    }
}

int main()
{
    Thread2 t1,t2;
    t1.setCallback(fun1);
    t2.setCallback(fun2);

    t1.start();
    t2.start();
    latch.wait();
    cout<<"end"<<endl;
}

参考:muduo多线程编程

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值