2

I want to write some code that on the main it will start some thread that will run every 2 seconds and will print something on the console.

the start function need to be something like this

     void StartTask(void* methodRoRun, long repeatTimeInSeconds);

that mean that the method receive pointer to function (methodRoRun) that will run every repeatTimeInSeconds seconds.

I can't find how to do it in C++

Yanshof
  • 9,659
  • 21
  • 95
  • 195
  • 1
    Can you be more specific about what help you need? Do you know how to create a thread? – David Schwartz Dec 21 '18 at 20:13
  • 2
    Break your desires into steps and focus on one step at a time. It looks like you want to know how to create a thread, how to make and use a timer, how to callback on a timer, how to pass around function pointers to threads, and maybe more. That's alot to cover for one post. – Christopher Pisz Dec 21 '18 at 20:15
  • Does `repeatTimeInSeconds` include time used by `methodRoRun` ? – Jarod42 Dec 21 '18 at 20:15
  • Your interface is so old. how about `void StartTask(std::function f, std::chrono::seconds repeatTime);` ? – Jarod42 Dec 21 '18 at 20:18
  • 1
    [`std::async`](https://en.cppreference.com/w/cpp/thread/async) is arguably the easiest way to safely manage asynchronous tasks. However, you'll still need a good understanding of synchronizations and how to avoid race conditions. – François Andrieux Dec 21 '18 at 20:21
  • 2
    You can't safely assign a function pointer to `void*`. See https://stackoverflow.com/a/5579907/7359094 – François Andrieux Dec 21 '18 at 20:21

1 Answers1

0

Something like this:

#include <thread>
#include <functional>

void f() {
    printf("Task started\n");
    // do stuff
}

void StartTask(std::function<void()> methodRoRun, long repeatTimeInSeconds) {
    std::thread th([methodRoRun, repeatTimeInSeconds]() {
        while (true ) {
            methodRoRun();
            std::this_thread::sleep_for(std::chrono::seconds(repeatTimeInSeconds));
        }
    });
    th.detach();
}

int main() {
    StartTask([](){ f(); }, 1);

    while (true) {}

    return 0;
}

Edit:

People are correctly pointing out this that detaching threads and having endless loops is not good practice, but the example just illustrates the approach.

Georgi Gerganov
  • 1,006
  • 9
  • 17