SleepAndRun()和ThreadFunc()在这段代码中做了什么?

时间:2018-06-09 09:32:01

标签: multithreading c++11 timer

我想为我的代码实现timer.h。所以我在网上冲浪,发现这段代码工作正常。但我想知道这个代码中的 SleepAndRun() ThreadFunc()做了什么以及为什么他这样定义? 用于异步代码执行的线程。我只知道在std :: this_thread :: sleep_for(interval)中是this_thread-当前theard创建了定时器对象         sleep_for()会阻塞线程的间隔,但为什么在这里使用?

    class Timer { std::thread Thread;

    bool Alive = false;
    long CallNumber = -1L;//no. of times function going to call
    long repeat_count = -1L;//no. of times function already called

    std::chrono::milliseconds interval = std::chrono::milliseconds(0);

    std::function<void(void)> funct = nullptr;

        void SleepAndRun ()
            {
            std::this_thread::sleep_for(interval);
            if (Alive)
                Function ()();
            } 

        void ThreadFunc ()
            {
            if (CallNumber == Infinite)
                while (Alive)
                    SleepAndRun ();
            else
                while (repeat_count--)
                    SleepAndRun ();
            }

        public: static const long Infinite = -1L;
 Timer () {} 

    Timer(const std::function<void(void)> &f) : funct (f) {}

    Timer(const std::function<void(void)> &f,
          const unsigned long &i,
          const long repeat = Timer::Infinite) : funct (f),
                                                 interval (std::chrono::milliseconds(i)), CallNumber (repeat) {}



    void Start (bool Async = true)
        {

        if (IsAlive ())//FOUNDING NOT ALIVE .THN alive =true
            return;

        Alive = true;

        repeat_count = CallNumber;

        if (Async)
            Thread = std::thread(ThreadFunc, this);
        else 
            this->ThreadFunc ();
        }

    void Stop ()
        {

        Alive = false;


        Thread.join ();
        }
    void SetFunction (const std::function<void (void)> &f)
        {
        funct = f;
        }
    bool IsAlive () const {return Alive;}
    void RepeatCount (const long r)
        {

        if (Alive)
            return;
        CallNumber = r;
        }

    long GetLeftCount () const {return repeat_count;}

    long RepeatCount () const {return CallNumber;}
    void SetInterval (const unsigned long &i)
        {

        if (Alive)
            return;;

        interval = std::chrono::milliseconds(i);
        }

    unsigned long Interval () const {return interval.count();}

    const std::function<void(void)> &Function () const
        {

        return funct;
        }
    };

1 个答案:

答案 0 :(得分:0)

调用Start()时,将运行方法ThreadFunc()。如果参数Asyncfalse,这将立即发生(即在当前线程中)。如果Asynctrue(这是您在没有参数的情况下调用Start()时的默认设置),则会创建一个新线程并在该线程中运行ThreadFunc()

ThreadFunc()现在调用SleepAndRun ()等待一段时间,该时间必须通过调用SetInterval() 以前来设置。它调用一个函数,您还必须通过调用SetFunction()来设置以前SetFunction()的参数类型为std::function<void()>,这意味着这可以是不带参数且不返回任何结果的任何函数。

为什么这样做?允许

的灵活性
  • 在相同或不同的线程中运行
  • 调用您在运行时提供的功能