C ++ 11 packaged_task移动语法 [英] C++11 packaged_task move syntax

查看:60
本文介绍了C ++ 11 packaged_task移动语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

稍微查看一下这段代码:

  //   packaged_task example  
#include < ; iostream > // std :: cout
#include < future > // std :: packaged_task,std :: future
#include < chrono < span class =code-keyword>> // std :: chrono :: seconds
#include < thread > // std :: thread,std :: this_thread :: sleep_for

// 每个值倒计时一秒:
int 倒计时( int from, int to){
for int i = from; !I =到; --i){
std :: cout<< i<< ' \ n';
std :: this_thread :: sleep_for(std :: chrono :: seconds( 1 ));
}
std :: cout<< 取消!\ n;
返回 from-to;
}

int main()
{
std :: packaged_task< int( int int )> tsk(倒计时); // 设置packaged_task
std :: future< int> ret = tsk.get_future(); // get future

std :: thread th(std :: move(tsk), 10 0 ) ; // 产生线程从10倒数到0

// ...

int value = ret.get(); // 等待任务完成并获得结果

std :: cout<< 倒计时持续了<< value << seconds.\\\
;

th.join();

return 0 ;
}





我不明白ret在这一行之后是如何与tsk相关的:

 std ::  thread  th(std :: move(tsk), 10  0 

我的意思是在此行之后tsk将为null或已损坏,然后有一个

  int   value  = ret.get()

这将从此null tsk获取内容,而不是来自线程内的任务th。

那么为什么会这样?

解决方案

未来是在之前获得的。因此,即使 move 在未定义的状态下离开 tsk ,未来将检索可调用的结果(倒计时)已经获得。



移动不破坏参数,它创建一个xvalue,所以线程 th 将通过 packaged_task

Look at this code a little bit:

// packaged_task example
#include <iostream>     // std::cout
#include <future>       // std::packaged_task, std::future
#include <chrono>       // std::chrono::seconds
#include <thread>       // std::thread, std::this_thread::sleep_for

// count down taking a second for each value:
int countdown (int from, int to) {
  for (int i=from; i!=to; --i) {
    std::cout << i << '\n';
    std::this_thread::sleep_for(std::chrono::seconds(1));
  }
  std::cout << "Lift off!\n";
  return from-to;
}

int main ()
{
  std::packaged_task<int(int,int)> tsk (countdown);   // set up packaged_task
  std::future<int> ret = tsk.get_future();            // get future

  std::thread th (std::move(tsk),10,0);   // spawn thread to count down from 10 to 0

  // ...

  int value = ret.get();                  // wait for the task to finish and get result

  std::cout << "The countdown lasted for " << value << " seconds.\n";

  th.join();

  return 0;
}



What I dont understand is how does ret relate to tsk after this line :

std::thread th (std::move(tsk),10,0)

I mean tsk will be null or corrupted after this line, and then one has

int value = ret.get()

which will get something from this null tsk and not from the task inside thread th.
So why does it work?

解决方案

The future is gotten before the move. So even if the move were to leave tsk in an undefined state, the future that will retrieve the result of the callable (countdown) is already gotten.

move doesn't destroy the parameter, it creates a xvalue, so the thread th will have a valid reference to the callable via the packaged_task.


这篇关于C ++ 11 packaged_task移动语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆