in the below code, there is parallel_for loop implemented with PPL. The main problem is here; abc vector values is not correct when i was commented cs.lock() and cs.unlock(). I am using concurrency_vector type for randomly access array values but it seems not working. Locking critical section, it's working but slow. Also, for speed up, i used indexing for storing values, not used 2D-concurrency_vector. What is the problem, without locking critical section, what i missed?

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

using namespace concurrency;
using namespace std;

int test_function()
{
    critical_section cs;

    concurrent_vector< double > abc( 300 * 400, 1000 );

    parallel_for ( 0, 1000, [ & ]( int k ) {
        for ( int y = 0; y < 300; y++ ) {
            for ( int x = 0; x < 400; x++ ) {

                /// k is using with some calculations for thr

                cs.lock();

                if ( thr < abc[ 400 * y + x ] ) {

                    abc[ 400 * y + x ] = thr;
                }

                cs.unlock();
            }
        }
    } );
}
有帮助吗?

解决方案

Why would you expect it to work? If this runs in parallel without locking, abc[400*y+x] can and will be changed between the if-statement and the assignment, thus breaking your logic. The vector type itself being thread-safe has nothing to do with this.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top