0

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();
            }
        }
    } );
}
user2055437
  • 67
  • 1
  • 13

1 Answers1

2

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.

Cubic
  • 14,902
  • 5
  • 47
  • 92
  • thank you for quick answer, am i correct, if-statement is causing the problem and we should protect it? – user2055437 Feb 16 '13 at 10:11
  • @user2055437 That seems to be the case, unless you have other things in your calculations that might break it. And of course this will be slow - locking/unlocking is slow and you need to do a lot of it. You also end up with a lot of unnecessary waiting. You might see some performance improvement if you use granular locks instead (create 300*400 critical sections, one for each element of abc, and then use those for locking). – Cubic Feb 16 '13 at 10:15
  • i'm sorry stealing your time, can you give some code block example or example sites, book that i can read for last you say speed up? – user2055437 Feb 16 '13 at 10:21
  • @user2055437 It _might_ speed it up (it probably will, actually). I'd love to do this in chat, unfortunately you need 20 rep to talk there. Basically, instead `critical_section cs;` `critical_section css[300*400]` and instead of `cs.lock()` / `cs.unlock()` `cs[400*y+x].lock()`/`cs[400*y+x].unlock()`. I'm not sure how expensive creating and holding critical sections is so I'm not sure if this helps, but if they're as inexpensive as I think then this should improve things. – Cubic Feb 16 '13 at 10:42