如何在不停止应用程序的情况下延迟功能

sum*_*ang 3 c++ visual-c++ c++11

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;
}
Run Code Online (Sandbox Code Playgroud)

我想延迟功能,但我的应用程序应继续运行。

在上面的代码中,我要先打印第一个值。比我想要Command2要打印,而Command1应该是最后要打印的。

Jen*_*ens 5

我喜欢std::async这个。

#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;
}
Run Code Online (Sandbox Code Playgroud)

但是,对于实际设计,我将创建一个调度程序(或最好使用现有的调度程序)来管理按延迟时间排序的优先级队列。为每个命令生成一个新线程将很快成为一个问题。由于您已标记了MS VIsual C ++的问题,因此请看一下实现基于任务的并行性的PPL

而作为它一个C ++的问题,我想从C的东西敬而远之,而不是使用printfCLOCK_PER_SECchar*clock等你会很快进入的问题,即使这个简单的例子,当你开始使用的字符串,而不是“命令1”文字。std::string将在这里为您提供帮助。


RBa*_*jee 0

根据您的实际逻辑,您可以通过多种方式来实现。例子;:

1.您可以使用全局标志变量并检查其状态,当第三次打印完成时,您可以将标志设置为1,以便执行下一个调用。

2.您可以使用 STACK .push 所有函数指针在 STACK 中。然后弹出并执行。

3.多线程。您可以通过适当的同步方式使用它,但这会很复杂。这取决于您的要求。

谢谢 !!!