如何在Windows中用C ++创建计时器

时间:2013-06-15 18:22:15

标签: c++

是否可以通过SetTimer或在C ++中在Windows中创建计时器 一些其他函数,其中回调函数将是一个类成员函数

1 个答案:

答案 0 :(得分:2)

是。

创建非静态类方法的定时回调的最简单方法是使用lambda捕获。这个例子是普通的C ++(C ++ 11)。它适用于例如Visual Studio 2012(添加了'2012年11月的CTP')或gcc 4.7.2或更高版本。

请注意,您需要尊重多线程编程的困难,因为回调是在“另一个”线程上到达的。我强烈建议您阅读Anthony Williams的书“ C ++ Concurrency in Action:Practical Multithreading”。

#include <future>
#include <iostream>
#include <chrono>
#include <thread>
#include <atomic>

class C {
  std::atomic<int> i;
public:
  C(int ini) :i(ini) {}
  int get_value() const {
    return i;
  }
  void set_value(int ini){
    i=ini;
  }
};

int main(){
  C c(75);
  auto timer=std::async(std::launch::async,[&c](){
    std::this_thread::sleep_for(std::chrono::milliseconds(1000) );
    std::cout << "value: "<< c.get_value()<<std::endl;
    });

  std::cout << "value original: " << c.get_value() <<std::endl;

  c.set_value(5);
  // do anything here:

  // wait for the timeout 
  timer.wait(); 
}