concurrent_vector在parallel_for(PPL)中不起作用

时间:2013-02-23 13:26:14

标签: c++ concurrency parallel-processing ppl parallel-for

下面有一个示例工作代码(parallel_for使用并行模式库(ppl))。这里的主要问题是 sqr < concurrent_vector>存储的值在每次执行时都会发生变化,但不应该是!

我用过< concurrent_vector>随机访问为什么它不起作用?

#include <iostream>
#include <ppl.h>
#include <concurrent_vector.h>

using namespace std;
using namespace concurrency;

const int a = 10, b = 30;

critical_section cs;

int main() {

    concurrent_vector< int > labels( a * b );

    concurrent_vector< int > sqr( 5 );

    // filling label vector
    for ( int y = 0; y < b; y++ ) {
        for ( int x = 0; x < a; x++ ) {

            if( x<2 && y>3 )
                labels[ a * y + x ] = 1;
            else if( x<30 && y<5 )
                labels[ a * y + x ] = 2;
            else if( x>5 && y>10 )
                labels[ a * y + x ] = 3;
            else if( x>2 && y>20 )
                labels[ a * y + x ] = 4;
        }
    }

    // printing
    for ( int y = 0; y < b; y++ ) {
        for ( int x = 0; x < a; x++ ) {

            cout << labels[ a * y + x ] << ", ";
        }
        cout << endl;
    }

    parallel_for ( 0, b, [ & ]( int y ) {
        for ( int x = 0; x < a; x++ ) {

            //cs.lock();  // when i used it's working but slow
            int i = labels[ a * y + x ];
            //cs.unlock();

            if ( i < 0 ) continue;

            sqr[ i ] ++;
        }
    } );

    for( int i=0; i<5; i++ )
        cout << sqr[i] << ", ";
    cout << "" << endl;

    system ("pause");

    return 0;
}

2 个答案:

答案 0 :(得分:2)

您没有使用与并发相关的并发向量的任何功能。实际上,你可以用标准向量替换它而没有区别......显然,i的值在每次执行内核时都会重叠。绝对不能保证对向量的同一元素的并发写入是同步的。因此,你得到随机结果 - 这只是非原子写入数据竞争的结果。

答案 1 :(得分:-1)

使用task_group::wait方法应该更快(因为您不必每次都锁定/解锁),它可能会按预期工作。

  

此方法阻止当前任务,直到另一个任务的任务   小组已经完成了他们的工作。

请参阅MSDN:Parallel Tasks

更新:我已经运行了一些时序测试,似乎这不是一个解决方案(除了我的双核上的大数据输入都失败)。 这可能是英特尔TBB中“concurrent_vector”中的“design”错误 - tbb::concurrent_vector returns wrong size

相关问题