Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delay a function without stopping the application

void sendCommand(float t,char* cmd)
{

  std::clock_t endwait; 
  double endwait = clock () + t * CLOCKS_PER_SEC ; 
  while (clock() < endwait) {} 
  if( clock() < endwait)
  printf("\nThe waited command is =%s",cmd);

}

void Main()
{
 sendCommand(3.0,"Command1");
 sendCommand(2.0,"Command2");
 printf("\nThe first value")
 return 0;
}

i want to delay a function but my application should keep on running.

In the above code i want The first value to be printed first. than i want Command2 to be printed and Command1 should be the last to be printed.

like image 734
sumit kang Avatar asked Sep 18 '15 03:09

sumit kang


2 Answers

I prefer std::async for this.

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

void sendCommand(std::chrono::seconds delay, std::string cmd)
{
     std::this_thread::sleep_for( delay );
     std::cout << "\nThe waited command is =" << cmd;
}

int main()
{
 auto s1 = std::async(std::launch::async, sendCommand, std::chrono::seconds(3),"Command1");
 auto s2 = std::async(std::launch::async, sendCommand, std::chrono::seconds(2),"Command2");

 std::cout << "\nThe first value" << std::flush;    
 s1.wait();
 s2.wait();


 return 0;
}

However, for a real design, I would create a scheduler (or preferably use an existing one) which manages a priority queue sorted by the delay time. Spawning a new thread for every command will quickly become a problem. Since you flagged the question for MS VIsual C++, take a look the PPL which implements task-based parallelism.

And as it a C++ question, I would stay away from the C stuff and not use printf, CLOCK_PER_SEC, char*, clock etc. You will quickly get into problems even with this simple example when you start using strings instead of the "Command1" literals. std::string will help you here.

like image 111
Jens Avatar answered Sep 27 '22 19:09

Jens


I think you need threads. You can do it like this:

#include <thread>
#include <chrono>
#include <iostream>

void sendCommand(float t, char const* cmd)
{
    std::this_thread::sleep_for(std::chrono::milliseconds(int(t * 1000)));
    std::cout << "\nThe waited command is = " << cmd << '\n';
}

int main()
{
    // each function call on a new thread
    std::thread t1(sendCommand, 3.0, "Command1");
    std::thread t2(sendCommand, 2.0, "Command2");

    // join the threads so we don't exit before they finish.
    t1.join();
    t2.join();
}
like image 34
Galik Avatar answered Sep 27 '22 18:09

Galik