下面有一个示例工作代码(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;
}