0

In a command line application I'm building I'd like to have two "processes" running at the same time. By processes, I mean such as:

Every 57 seconds, I would like to do task A, and every 250 seconds do task B. Those are arbitrarily chosen numbers, but you get the point.

How can I have both of these "processes" being checked at the same time?

Thanks guys

Josh Beckwith
  • 1,432
  • 3
  • 20
  • 38

3 Answers3

2

You could do something like this, if neither of the process takes long.

float Atime = 57.f;
float Btime = 250.f;
float startTime = someTimerFunc();
while(true) {
    sleep(a few milliseconds);


    float endTime = someTimerFunc();
    float deltaTime = endTime - startTime;
    startTime = endTime;



    Atime -= deltaTime;
    Btime -= deltaTime;
    if(Atime < 0) {
        Atime += 57.f;
        AProcess();
    }
    if(Btime < 0) {
        Btime += 250.f;
        BProcess();
    }
}

Or you could look up what threads do.

BWG
  • 2,238
  • 1
  • 20
  • 32
2

Running 2 threads would be a good way to handle this unless you have a reason to need different processes. Something like this:

void taskA() { /*...*/ }
void taskB() { /*...*/ }

/*...*/

bool exit = false;
std::mutex mutex;
std::condition_variable cv;

auto runLoop = [&](auto duration, auto task)
    {
        std::unique_lock<std::mutex> lock{mutex};

        while(true)
        {
            if(!cv.wait_for(lock, duration, [&]{ return !exit; }))
                task();
            else
                return;
        }
    };

std::thread a{ [&]{ runLoop(std::chrono::seconds{57}, taskA); }};
std::thread b{ [&]{ runLoop(std::chrono::seconds{250}, taskB); }};

Doing it this way is cross platform standard C++, which is a major benefit. It uses C++11: lambdas and threading library.

David
  • 27,652
  • 18
  • 89
  • 138
1

As said above, you can use threads instead of processes. If you are using c++11, have a look here on how you can create a thread.

In the example of the link, just replace foo and bar with the code that you want task A and task B to execute.

Also you can have a look here for how you can make your program wait for some time with sleep.

opetroch
  • 3,929
  • 2
  • 22
  • 24