2

i want to have a timer running in the background of my program while i do other stuff.

My program looks like:

void timer(int number)
{
    std::this_thread::sleep_for(std::chrono::seconds(number));
    std::cout << "executing someFunction()";
}

int function1()
{
    int number = 3;
    auto future = std::async(timer, number)

    int choice;
    std::cout << "please enter a number: ";
    std::cin >> choice;
    while (choice != 0)
    {
        std::cout << choice << std::endl;
        std::cout << "please enter a number: ";
        std::cin >> choice;
    }
    return 1;
}

int main()
{
    int num_rows = function1();
}

Headers are:

#include <iostream>
#include <chrono>
#include <future>

Problem is, after calling the function "timer" with async, it doesn't stop which causes function1 to be stuck as well.

I've understood there is no option to cancel a thread (yet) and to do so I have to pass an "atomic variable" flag to the async task. Could someone please show me an example?

other sources:
c++ background timer (stackoverflow)
is there a way to cancel/detach a future in c++11? (stackoverflow)

Community
  • 1
  • 1
Gerdinand
  • 81
  • 2
  • 9
  • Your code doesn't compile because `auto timer` conflicts with `timer` function name – billz Feb 04 '13 at 07:46
  • mac os x. Is there a platform independent way to get the background timer? – Gerdinand Feb 04 '13 at 07:47
  • ah sorry, my mistake. i didnt copy & paste and changed some names to keep the code easier to read. my original code has different names. – Gerdinand Feb 04 '13 at 07:49
  • I've never worked with Qt before and prefer Xcode since i just learned how to use it. another solution could be ending `std::this_thread::sleep_for(std::chrono::seconds(number));` is that even possible? – Gerdinand Feb 04 '13 at 11:26

0 Answers0