简体   繁体   English

使用TBB在向量中运行函数会产生错误的输出

[英]Running functions in a vector using TBB gives incorrect output

Here is my code which is supposed to write the numbers 0 to 19 on the screen (in random order). 这是我的代码,它应该在屏幕上写出数字0到19(按随机顺序)。

vector<std::function<void(void)>> tasks;
for(int i=0; i<20;i++)
     { 
        tasks.push_back( [&](){cout<< i<<endl;} );  
     }

tbb::parallel_for(size_t(0), size_t(tasks.size()), [&](int K) {(tasks[K])();});

The out out is: 出局是:

20
20
20
20
20
20
20
20
20
20
20
20
20
20
20
20
20
20
20
20

What am I doing wrong? 我究竟做错了什么? How can I make it to write out the numbers 0 to 19? 怎样才能写出0到19的数字?

You passed a reference to i when adding the new task: 在添加新任务时,您传递了对i引用

  tasks.push_back( [&](){cout<< i<<endl;} ); // ^^^ here 

When the task is run, i has reached 20, so that's what each thread will print. 当任务运行时, i已达到20,这就是每个线程将打印的内容。

Instead, you probably want to capture a copy of i : 相反,您可能想要捕获i副本

    tasks.push_back([=i]{ std::cout << i << '\n'; });

(The = is optional there; I included it to make the point clearer) (那里的=是可选的;我把它包括在内以使点更清晰)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM