C++ - constantly increment an integer

1.2k views Asked by At

I'm looking for a way to have an integer be constantly incremented every 10 seconds or so. I know how to get the integer to increment, but I don't know how to get it to continue to increment no matter what else is currently occurring in the rest of the program.

2

There are 2 answers

3
bhavesh On

Use std::thread for this.

Create a function

void incrementThread(int &i)
{
  while(someCondition)
  {
    //sleep for 10 seconds
    //increment your value
    i++;
    std::this_thread::sleep_for(std::chrono::duration<int>(10));
  }
}

Now from main:

int main()
{
  int i = 0;
  std::thread t(incrementThread, std::ref(i));
  t.detach() // or t.join()
}
0
WiSaGaN On

Using C++11 style:

#include <atomic>
#include <iostream>
#include <thread>

int main()
{
    std::atomic<int> i{0};
    std::thread thread_time([&]() { while (true) { ++i; std::this_thread::sleep_for(std::chrono::seconds(10)); } });
    while (true) {
        std::cout << i.load() << std::endl;
        std::this_thread::sleep_for(std::chrono::seconds(10));
    }
    thread_time.join();
    return 0;
}