user1913557
user1913557

Reputation: 99

How to create timer in Windows in C++

Is it possible to create a timer in Windows in C++ , by SetTimer or some other function, where a callback function will be a class member function

Upvotes: 1

Views: 2333

Answers (1)

Johan Lundberg
Johan Lundberg

Reputation: 27058

Yes.

The easiest way to create a timed callback to a non-static class method is to use lambda captures. This example is plain C++ (C++11). It works fine with for example Visual Studio 2012 (with the 'CTP November 2012' addition) or gcc 4.7.2 or later.

Note that you need to be respect the difficulties of multi-threaded programming since the callback is arriving on 'another' thread. I strongly recommend getting the book C++ Concurrency in Action: Practical Multithreading' by Anthony Williams.

#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(); 
}

Upvotes: 2

Related Questions