聯(lián)系我們 - 廣告服務(wù) - 聯(lián)系電話:
您的當(dāng)前位置: > 關(guān)注 > > 正文

何刪除定時(shí)器?MyLibco協(xié)程網(wǎng)絡(luò)庫定時(shí)器的設(shè)計(jì)

來源:CSDN 時(shí)間:2023-01-28 13:52:43

時(shí)間戳類(基本摘自muduo)

//Timestamp.h

namespace Tattoo{class Timestamp{public:    Timestamp();    explicit Timestamp(int64_t microSecondsSinceEpoch);    void swap(Timestamp &that)    {std::swap(microSecondsSinceEpoch_, that.microSecondsSinceEpoch_);    }    std::string toString() const;    std::string toFormattedString() const;    //微妙大于0就是 valid 的    bool valid() const {return microSecondsSinceEpoch_ > 0; }    int64_t microSecondsSinceEpoch() const {return microSecondsSinceEpoch_; }    //微秒轉(zhuǎn)化為秒    time_t secondsSinceEpoch() const    {return static_cast(microSecondsSinceEpoch_ / kMicroSecondsPerSecond);    }    //得到現(xiàn)在的時(shí)間    static Timestamp now();    //獲取一個(gè)無效時(shí)間,即時(shí)間等于0    static Timestamp invalid();    //一百萬,一微秒等于百萬分之一秒    static const int kMicroSecondsPerSecond = 1000 * 1000;  private:    int64_t microSecondsSinceEpoch_;};// 這里重載 < 號(hào),在下文的multimap 中就會(huì)用到inline bool operator<(Timestamp lhs, Timestamp rhs){return lhs.microSecondsSinceEpoch() < rhs.microSecondsSinceEpoch();}inline bool operator==(Timestamp lhs, Timestamp rhs){return lhs.microSecondsSinceEpoch() == rhs.microSecondsSinceEpoch();}將返回兩個(gè)事件時(shí)間差的秒數(shù),注意單位!inline double timeDifference(Timestamp high, Timestamp low){int64_t diff = high.microSecondsSinceEpoch() - low.microSecondsSinceEpoch();    return static_cast(diff) / Timestamp::kMicroSecondsPerSecond;}//把秒轉(zhuǎn)化為微秒,構(gòu)造一個(gè)對(duì)象,再把它們的時(shí)間加起來,構(gòu)造一個(gè)無名臨時(shí)對(duì)象返回inline Timestamp addTime(Timestamp timestamp, double seconds){int64_t delta = static_cast(seconds * Timestamp::kMicroSecondsPerSecond);    return Timestamp(timestamp.microSecondsSinceEpoch() + delta);}} // namespace Tattoo


(資料圖片僅供參考)

//Timestamp.cpp

using namespace Tattoo;Timestamp::Timestamp()    : microSecondsSinceEpoch_(0){}Timestamp::Timestamp(int64_t microseconds)    : microSecondsSinceEpoch_(microseconds){}std::string Timestamp::toString() const{char buf[32] = {0};    int64_t seconds = microSecondsSinceEpoch_ / kMicroSecondsPerSecond;    int64_t microseconds = microSecondsSinceEpoch_ % kMicroSecondsPerSecond;    //PRId64跨平臺(tái)打印64位整數(shù),因?yàn)閕nt64_t用來表示64位整數(shù),在32位系統(tǒng)中是long long int,64位系統(tǒng)中是long int    //所以打印64位是%ld或%lld,可移植性較差,不如統(tǒng)一同PRID64來打印。    snprintf(buf, sizeof(buf) - 1, "%" PRId64 ".%06" PRId64 "", seconds, microseconds);    return buf;}//把它轉(zhuǎn)換成一個(gè)格式化字符串std::string Timestamp::toFormattedString() const{char buf[32] = {0};    time_t seconds = static_cast(microSecondsSinceEpoch_ / kMicroSecondsPerSecond);    int microseconds = static_cast(microSecondsSinceEpoch_ % kMicroSecondsPerSecond);    struct tm tm_time;    gmtime_r(&seconds, &tm_time);    snprintf(buf, sizeof(buf), "%4d%02d%02d %02d:%02d:%02d.%06d",             tm_time.tm_year + 1900, tm_time.tm_mon + 1, tm_time.tm_mday,             tm_time.tm_hour, tm_time.tm_min, tm_time.tm_sec,             microseconds);    return buf;}Timestamp Timestamp::now(){struct timeval tv;    gettimeofday(&tv, NULL);     //獲得當(dāng)前時(shí)間,第二個(gè)參數(shù)是一個(gè)時(shí)區(qū),當(dāng)前不需要返回時(shí)區(qū),就填空指針    int64_t seconds = tv.tv_sec; //取出秒數(shù)    return Timestamp(seconds * kMicroSecondsPerSecond + tv.tv_usec);}Timestamp Timestamp::invalid(){return Timestamp();}

定時(shí)器

在這里,我是直接讓協(xié)程在一段時(shí)間之后喚醒即可(runAfter),至于需不需要 repeat ,這個(gè)我也在思考當(dāng)中,以后了解到了再加吧!!學(xué)習(xí)也就是一點(diǎn)一點(diǎn)積累的過程啦!!! //Timer.h

/*定時(shí)器類*/class Timer{public:    Timer(Timestamp when);    Timestamp expiration() const {return expire_; }    void run() const;    Timestamp expire_; //任務(wù)的超時(shí)時(shí)間    Routine_t *timer_rou_;};

//Timer.cpp

Timer::Timer(Timestamp when)    : timer_rou_(get_curr_routine()), //一個(gè)定時(shí)器對(duì)應(yīng)一個(gè)協(xié)程      expire_(when){}void Timer::run() const{cout << "由定時(shí)器喚醒對(duì)應(yīng)協(xié)程" << endl;    timer_rou_->Resume();}

定時(shí)器容器

.h 文件

class TimeHeap{public:    TimeHeap(EventLoop *loop);    ~TimeHeap();    Timer *addTimer(Timestamp when);    void delTimer(Timer *timer);  private:    typedef std::pairEntry;    typedef std::multimapTimerMap;    // 超時(shí)之后的可讀回調(diào)    void handleRead();    std::vectorgetExpired(Timestamp now);        /* 重置超時(shí)的定時(shí)器 */    void reset(const std::vector&expired, Timestamp now);    bool insert(Timer *timer);    EventLoop *loop_;    const int timerfd_;    Channel timerfdChannel_;    TimerMap timers_;};

.cpp 文件

namespace Tattoo{namespace detail{//創(chuàng)建 timerfdint createTimerfd(){int timerfd = ::timerfd_create(CLOCK_MONOTONIC,                                   TFD_NONBLOCK | TFD_CLOEXEC);    if (timerfd < 0)    {std::cout << "Failed in timerfd_create" << std::endl;    }    return timerfd;}/* 計(jì)算超時(shí)時(shí)間與當(dāng)前時(shí)間的時(shí)間差,并將參數(shù)轉(zhuǎn)換為 api 接受的類型  */struct timespec howMuchTimeFromNow(Timestamp when){/* 微秒數(shù) = 超時(shí)時(shí)刻微秒數(shù) - 當(dāng)前時(shí)刻微秒數(shù) */    int64_t microseconds = when.microSecondsSinceEpoch() - Timestamp::now().microSecondsSinceEpoch();    if (microseconds < 100)    {microseconds = 100;    }    struct timespec ts; // 轉(zhuǎn)換成 struct timespec 結(jié)構(gòu)返回    // tv_sec 秒    // tv_nsec 納秒    ts.tv_sec = static_cast(        microseconds / Timestamp::kMicroSecondsPerSecond);    ts.tv_nsec = static_cast(        (microseconds % Timestamp::kMicroSecondsPerSecond) * 1000);    return ts;}/* 讀timerfd,避免定時(shí)器事件一直觸發(fā) */void readTimerfd(int timerfd, Timestamp now){uint64_t howmany;    ssize_t n = ::read(timerfd, &howmany, sizeof(howmany));    std::cout << "TimerQueue::handleRead() " << howmany << " at " << now.toString() << std::endl;    if (n != sizeof howmany)    {std::cout << "TimerQueue::handleRead() reads " << n << " bytes instead of 8" << std::endl;    }}/* 重置 timerfd 的超時(shí)時(shí)間 */void resetTimerfd(int timerfd, Timestamp expiration){struct itimerspec newValue;    struct itimerspec oldValue;    bzero(&newValue, sizeof newValue);    bzero(&oldValue, sizeof oldValue);    newValue.it_value = howMuchTimeFromNow(expiration);    //到這個(gè)時(shí)間后,會(huì)產(chǎn)生一個(gè)定時(shí)事件    int ret = ::timerfd_settime(timerfd, 0, &newValue, &oldValue);    if (ret)    {std::cout << "timerfd_settime()" << std::endl;    }}} // namespace detail} // namespace Tattoousing namespace Tattoo;using namespace Tattoo::detail;TimeHeap::TimeHeap(EventLoop *loop)    : loop_(loop),      timerfd_(createTimerfd()),      timerfdChannel_(loop, timerfd_),      timers_(){// 設(shè)置自己獨(dú)特的回調(diào)函數(shù),并不是和普通的Channel 一樣,直接喚醒了對(duì)應(yīng)的協(xié)程    timerfdChannel_.setHandleCallback(        std::bind(&TimeHeap::handleRead, this));    timerfdChannel_.enableReading();}TimeHeap::~TimeHeap(){timerfdChannel_.disableAll();    ::close(timerfd_);    for (auto it = timers_.begin();         it != timers_.end(); ++it)    {delete it->second;    }}/* 添加一個(gè)定時(shí)器 ,返回定時(shí)器指針,會(huì)在 channel->addEpoll 函數(shù)中使用到,因?yàn)橐獎(jiǎng)h除對(duì)應(yīng)的定時(shí)器*/Timer *TimeHeap::addTimer(Timestamp when){Timer *timer = new Timer(when);    如果當(dāng)前插入的定時(shí)器 比隊(duì)列中的定時(shí)器都早 則返回真    bool earliestChanged = insert(timer);    //最早的超時(shí)時(shí)間改變了,就需要重置timerfd_的超時(shí)時(shí)間    if (earliestChanged)    {//timerfd_ 重新設(shè)置超時(shí)時(shí)間,使得 timerfd  的定時(shí)事件始終是最小的        resetTimerfd(timerfd_, timer->expiration());    }    return timer;}/* 刪除一個(gè)定時(shí)器 */void TimeHeap::delTimer(Timer *timer){auto it = timers_.find(timer->expire_);    if (it != timers_.end())    {timers_.erase(it);    }    return;}//timerfd 可讀 的回調(diào)void TimeHeap::handleRead(){Timestamp now(Timestamp::now());    //先讀取    readTimerfd(timerfd_, now);    std::vectorexpired = getExpired(now);    for (std::vector::iterator it = expired.begin();         it != expired.end(); ++it)    {it->second->run(); //run->Resume()    }    reset(expired, now); //這里主要是改變 timerfd 的定時(shí)最小值}//獲取所有超時(shí)的定時(shí)器std::vectorTimeHeap::getExpired(Timestamp now){std::vectorexpired;    auto it = timers_.lower_bound(now);    assert(it == timers_.end() || now < it->first);    std::copy(timers_.begin(), it, back_inserter(expired));    timers_.erase(timers_.begin(), it);    return expired;}void TimeHeap::reset(const std::vector&expired, Timestamp now){Timestamp nextExpire;    for (std::vector::const_iterator it = expired.begin();         it != expired.end(); ++it)    {delete it->second;    }    if (!timers_.empty()) //timers_ 不為空    {/*獲取當(dāng)前定時(shí)器集合中的最早定時(shí)器的時(shí)間戳,作為下次超時(shí)時(shí)間*/        nextExpire = timers_.begin()->second->expiration();    }    //如果取得的時(shí)間 >0就改變 timerfd 的定時(shí)    if (nextExpire.valid())    {resetTimerfd(timerfd_, nextExpire);    }}bool TimeHeap::insert(Timer *timer){bool earliestChanged = false;    Timestamp when = timer->expiration();    auto it = timers_.begin();    if (it == timers_.end() || when < it->first)    {earliestChanged = true;    }    timers_.insert(std::make_pair(when, timer));    return earliestChanged;}

OK,上面的就是具體的實(shí)現(xiàn)代碼了,下面來說一下幾個(gè)點(diǎn):

1.如何添加定時(shí)器?

在我寫的協(xié)程庫中是這樣實(shí)現(xiàn)的: Channel::addEpoll()->loop_->runAfter(10)->timerHeap_->addTimer()

2.如何刪除定時(shí)器?

loop_->cancel()->timerHeap_->delTimer()

3.如何將timerfd與Eventloop 統(tǒng)一起來?

首先來看一下eventloop:

.h

#include "Callbacks.h"#include "Timestamp.h"#include#include#include "routine.h"namespace Tattoo{class Channel;class Epoll;class TimeHeap;class Timer;class RoutineEnv_t;class EventLoop{public:    EventLoop();    ~EventLoop();    void loop();    // timers    Timer *runAt(const Timestamp &time);    Timer *runAfter(double delay);    void cancel(Timer *timer);    void updateChannel(Channel *channel);    void removeChannel(Channel *channel);  private:    typedef std::vectorChannelList;    Epoll *epoll_;    TimeHeap *timerHeap_;    ChannelList activeChannels_;    RoutineEnv_t *rouEnv_;};} // namespace Tattoo

.cpp

#include#include "Channel.h"#include "Epoll.h"#include "MiniHeap.h"#include "EventLoop.h"using namespace Tattoo;const int kPollTimeMs = 10000; // 10 sEventLoop::EventLoop()    : rouEnv_(get_curr_thread_env()), //  一個(gè) eventloop  對(duì)應(yīng)一個(gè) Routine_env      epoll_(new Epoll(this)),      timerHeap_(new TimeHeap(this))       //在TimeHead初始化時(shí),就會(huì)將 timerfd 加入 epoll 監(jiān)聽中{// std::cout << "EventLoop created " << this << std::endl;    rouEnv_->envEventLoop_ = this; //關(guān)鍵點(diǎn)}EventLoop::~EventLoop(){}void EventLoop::loop(){while (1)    {activeChannels_.clear();        int ret = epoll_->poll(kPollTimeMs, &activeChannels_);        for (auto it = activeChannels_.begin();             it != activeChannels_.end(); ++it)        {(*it)->handleEvent(); //事件分發(fā),記得注冊(cè)時(shí)間回調(diào)(一般就是 Resume())        }    }    std::cout << "EventLoop " << this << " stop looping" << std::endl;}Timer *EventLoop::runAt(const Timestamp &time){return timerHeap_->addTimer(time);}Timer *EventLoop::runAfter(double delay){Timestamp time(addTime(Timestamp::now(), delay));    runAt(time);}void EventLoop::cancel(Timer *timer){timerHeap_->delTimer(timer);}void EventLoop::updateChannel(Channel *channel){epoll_->updateChannel(channel);}void EventLoop::removeChannel(Channel *channel){epoll_->removeChannel(channel);}

4.定時(shí)器的組織方式(和 muduo 差不多,他用的是set,我用的是 multimap)

muduo定時(shí)器容器封裝了 Timer.h里面保存的是超時(shí)時(shí)間和回調(diào)函數(shù), TimerQueue.h使用set容器保存多個(gè)定時(shí)器, 然后在TimerQueue中使用timerfd_create創(chuàng)建一個(gè)timerfd句柄, 插入定時(shí)器A后先比較A的觸發(fā)時(shí)間和TimerQueue的觸發(fā)時(shí)間, 如果A的觸發(fā)時(shí)間比其小就使用timerfd_settime重置TimerQueue的timerfd的觸發(fā)時(shí)間, TimerQueue中的timerfd的觸發(fā)時(shí)間永遠(yuǎn)與保存的定時(shí)器中觸發(fā)時(shí)間最小的那個(gè)相同, 然后timerfd觸發(fā)可讀后, 遍歷保存的多個(gè)定時(shí)器, 看看有沒有同時(shí)到期的, 有執(zhí)行回調(diào)函數(shù)

4.協(xié)程庫中定時(shí)器的使用(與 libco 基本一樣)

先行閱讀:https://blog.csdn.net/liushengxi_root/article/details/88421955 主要函數(shù)(addEpoll):

void Channel::addEpoll(){//這里就設(shè)置的回調(diào)函數(shù)和 timerfd 設(shè)置的回調(diào)函數(shù)不一樣哦    setHandleCallback(std::bind(&Channel::handleFun, this));    events_ |= kReadEvent;    events_ |= kWriteEvent;    update();    Timer *tmp = loop_->runAfter(10);    //退出當(dāng)前協(xié)程    get_curr_routine()->Yield();    //刪除加入的 epoll 信息和對(duì)應(yīng)定時(shí)器    loop_->removeChannel(this);    loop_->cancel(tmp);}

事件到來會(huì)喚醒對(duì)應(yīng)的協(xié)程,時(shí)間超時(shí)時(shí) 也會(huì)喚醒對(duì)應(yīng)的協(xié)程(不會(huì)讓其一直阻塞下去)

主事件循環(huán)還是看上面的鏈接即可!!

運(yùn)行結(jié)果:

責(zé)任編輯:

標(biāo)簽:

相關(guān)推薦:

精彩放送:

新聞聚焦
Top