C++ 封装 eventfd

Eventfd.h

#pragma once
#include<sys/eventfd.h>
#include<functional>
using std::function;
namespace wd
{
    using EventfdCallBack = function<void()>;
    class Eventfd
    {
    public:
        Eventfd(EventfdCallBack&& cb);
        void start();
        void stop();

        void wakeup();//向_evfd中发送消息

    private:
        void handleRead();//读取_evfd中发送的数据
        int createEventfd();
    private:
        int _evfd;
        EventfdCallBack _cb;
        bool _isRunning;
    };
};

Eventfd.cpp

#include"Eventfd.h"
#include<sys/poll.h>
#include<string.h>
#include<errno.h>
#include<unistd.h>
namespace wd
{
    Eventfd::Eventfd(EventfdCallBack &&cb)
:_evfd(createEventfd()),_cb(cb),_isRunning(false)
{
}
void Eventfd::start()
{
    _isRunning =true;
    struct pollfd pfd;
    bzero(&pfd,sizeof(pfd));
    pfd.fd = _evfd;
    pfd.events = POLLIN;
    while(_isRunning)
    {
        int nready =poll(&pfd,1,5000);
        if(-1== nready && errno == EINTR)
        {
            continue;
        }
        else if(-1== nready)
        {
            perror("poll");
        }
        else if(0== nready)
        {
            printf("timeout\n");
        }
        else
        {
            handleRead();//先读取_evfd中的数据
            _cb();//再调⽤回调函数
        }
    }
}
void Eventfd::stop()
{
    if(_isRunning)
         _isRunning =false;
}
void Eventfd::wakeup()
{
    uint64_t event_write =1;
    if(write(_evfd,&event_write,sizeof(uint64_t))!=sizeof(uint64_t))
    {
        perror("write evfd");
    }
}
void Eventfd::handleRead()
{
    uint64_t event_read;
    if(read(_evfd,&event_read,sizeof(uint64_t))!=sizeof(uint64_t))
    {
        perror("read evfd");
    }
}
int Eventfd::createEventfd()
{
    int evfd =eventfd(0,0);
    if(-1== evfd)
    {
        perror("eventfd");
    }
    return evfd
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值