Home > OS >  How to do a task in background of c code without changing the runtime
How to do a task in background of c code without changing the runtime

Time:12-10

I was trying to create a bank system that has features for credit,deposit,transaction history etc. I wanted to add interest rate as well so I was thinking of adding it in after 10 seconds of delay but When I am using delay(like sleep()function). My whole program is delayed by 10 seconds. Is there a way for interest to be calculated in the background while my runtime of the code won't be affected?

CodePudding user response:

If you need just single task to be run then there exists std::async, which allows to run a task (function call) in a separate thread.

As you need to delay this task then just use std::sleep_for or std::sleep_until to add extra delay within async call. sleep_for shall be used if you want to wait for certain amount of seconds, and sleep_until shall be used if you want to wait till some point in time, e.g. to sleep until 11:32:40 time is reached.

In code below you can see that Doing Something 1 is run before start of async thread, then thread starts, which is waiting for 2 seconds, same time Doing Something 2 is called. After that you may wish (if so) to wait for delayed task to be finished, for that you call res.get(), this blocks main thread till async thread is fully finished. Afterwards Doing Something 3 is called.

If you don't do res.get() explicitly then async thread just finishes by itself at some point. Of if program is about to exit while async thread is still running, then program waits for this async thread to finish.

Try it online!

#include <future>
#include <chrono>
#include <thread>
#include <iostream>
#include <iomanip>

int main() {
    int some_value = 123;
    auto const tb = std::chrono::system_clock::now();
    auto Time = [&]{
        return std::chrono::duration_cast<std::chrono::duration<double>>(
            std::chrono::system_clock::now() - tb).count();
    };

    std::cout << std::fixed << std::setprecision(3);
    std::cout << "Doing Something 1... at "
        << Time() << " sec" << std::endl;

    auto res = std::async(std::launch::async, [&]{
        std::this_thread::sleep_for(std::chrono::seconds(2));
        std::cout << "Doing Delayed Task... at "
            << Time() << " sec, value " << some_value << std::endl;
    });

    std::cout << "Doing Something 2... at "
        << Time() << " sec" << std::endl;

    res.get();

    std::cout << "Doing Something 3... at "
        << Time() << " sec" << std::endl;
}

Output:

Doing Something 1... at 0.000 sec
Doing Something 2... at 0.000 sec
Doing Delayed Task... at 2.001 sec, value 123
Doing Something 3... at 2.001 sec
  •  Tags:  
  • c
  • Related