Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Multithreading 等待线程以时间限制加入_Multithreading_C++11_Asynchronous - Fatal编程技术网

Multithreading 等待线程以时间限制加入

Multithreading 等待线程以时间限制加入,multithreading,c++11,asynchronous,Multithreading,C++11,Asynchronous,我有一个线程,它使用参数params调用函数MyFunc。基本上,它在MyFunc运行时输出流中的点,超时500毫秒。我需要等待线程1分钟,如果函数在1分钟内完成其工作,则需要输出“MyFunc成功完成”,如果在1分钟后仍在运行,则需要输出“timeout”。我该怎么做 std::future<void> f = std::async(std::launch::async, MyFunc, params); std::chrono::milliseconds span(500);

我有一个线程,它使用参数
params
调用函数
MyFunc
。基本上,它在
MyFunc
运行时输出流中的点,超时500毫秒。我需要等待线程1分钟,如果函数在1分钟内完成其工作,则需要输出“MyFunc成功完成”,如果在1分钟后仍在运行,则需要输出“timeout”。我该怎么做

std::future<void> f = std::async(std::launch::async, MyFunc, params);

std::chrono::milliseconds span(500);
while (f.wait_for(span) == std::future_status::timeout)
    std::cout << '.';
std::future f=std::async(std::launch::async,MyFunc,params);
标准时间:毫秒跨度(500);
while(f.wait_for(span)=std::future_status::timeout)
std::cout您可以使用
wait_for()
,没有问题

std::future<void> f = std::async(std::launch::async, MyFunc, params);


auto because = std::async(std::launch::async,[&]() 
         {
           // for your use, you may want to change it from 0 seconds to something
           // like 1 second, or 500 ms
           while(f.wait_for(std::chrono::seconds(0)) != std::future_status::ready)
               std::cout << ".";
         }).wait_for(std::chrono::seconds(60));

if(because == std::future_status::ready) 
  std::cout << "Successfully Completed\n";
else
  std::cout << "Timeout";
std::future f=std::async(std::launch::async,MyFunc,params);
自动因为=std::async(std::launch::async,[&]()
{
//对于您的使用,您可能需要将其从0秒更改为其他值
//比如1秒,或者500毫秒
while(f.wait_for(std::chrono::seconds(0))!=std::future_status::ready)

std::cout记得你什么时候开始等待,或者计算你等待的次数。然后你在每次迭代中检查这些值,并确定是否超过1分钟。如果是这样,你就退出循环。

天哪,你16岁了吗?我16岁时做了什么。我吃了灰尘