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;
}
我想延迟某个功能,但我的应用程序应该继续运行。
在上面的代码中,我想首先打印第一个值。
比我希望打印 Command2 而 Command1 应该是最后打印的。
我更喜欢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;
}
然而,对于真正的设计,我会创建一个调度程序(或者最好使用现有的调度程序)来管理按延迟时间排序的优先级队列。为每个命令生成一个新线程很快就会成为一个问题。既然您标记了 MS VIsual C++ 的问题,请看一下实现基于任务的并行性的 PPL https://msdn.microsoft.com/en-us/library/dd492427.aspx.
由于这是一个 C++ 问题,我会远离 C 的东西并且不使用printf
, CLOCK_PER_SEC
, char*
, clock
当您开始使用字符串而不是“Command1”文字时,即使是这个简单的示例,您也会很快遇到问题。std::string
会在这里帮助你。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)