windows客户端开发--实现一个多线程定时器

来源:互联网 发布:php 二维数组重复 编辑:程序博客网 时间:2024/05/16 14:52

go了很久了,但是生活还得继续,工作还得继续,今天跟大家分享一个多线程的定时器。

Windows为我们提供了SetTimer和KillTimer
启动
SetTimer(m_hWnd, TESTWM_SENDDING_EMAIL_TIMER, 500, NULL);

响应
然后响应uMsg == TESTWM_SENDDING_EMAIL_TIMER

销毁
KillTimer(m_hWnd, TESTWM_SENDDING_EMAIL_TIMER);

实现一个多线程定时器
这里用标准C++写的,包括了一些C++11特性。

基本的知识之前的博客都有介绍:

时间库chrono库介绍:
C++11中的便利工具–chrono库(处理日期和时间)
http://blog.csdn.net/wangshubo1989/article/details/50507038

c++11 中线程介绍:
C++ 11特性之std::thread–初识
http://blog.csdn.net/wangshubo1989/article/details/49592517

C++11特性之std::thread–初识二
http://blog.csdn.net/wangshubo1989/article/details/49593429

C++11特性之std::thread–进阶
http://blog.csdn.net/wangshubo1989/article/details/49624575

c++11特性之std::thread–进阶二
http://blog.csdn.net/wangshubo1989/article/details/49624669

言归正传,实现一个多线程定时器:

#ifndef TIMER_H_#define TIMER_H_#include <thread>#include <chrono>class Timer{    std::thread th;    bool running = false;public:    typedef std::chrono::milliseconds Interval;    typedef std::function<void(void)> Timeout;    void start(const Interval &interval,        const Timeout &timeout)    {        running = true;        th = std::thread([=]()        {            while (running == true) {                std::this_thread::sleep_for(interval);                timeout();            }        });    }    void stop()    {        running = false;        if (th.joinable())        {            th.join();        }    }};#endif  // TIMER_H_

这里写图片描述

1 0
原创粉丝点击