Community
cancel
Showing results for 
Search instead for 
Did you mean: 
yingemmachen
Beginner
52 Views

How can I use parallel_for to pass two dimensional arrays?

Hi,

I tried to use parallel_for to speed up our c++ program. It seems very easy to use. However, in the function which is to be parallelized, a few 2D arrays calculated in the function need be passed to the main funciton. In the example (sub_string_finder.cpp), one dimensional arrays are modified in the SubStringFinder by using the addresses of these arrays. Please see the code below. I am wondering if I can use similar trick, but not sure how to use it on 2D arrays.

Thanks,
Ying

--------------------------------------------------------------------------------------------------------------

#include
#include
#include

#include "tbb/parallel_for.h"
#include "tbb/blocked_range.h"

using namespace tbb;
using namespace std;

static const size_t N = 23;

class SubStringFinder {
const string str;
size_t *max_array;
size_t *pos_array;
public:
void operator() ( const blocked_range& r ) const {
for ( size_t i = r.begin(); i != r.end(); ++i ) {
size_t max_size = 0, max_pos = 0;
for (size_t j = 0; j < str.size(); ++j)
if (j != i) {
size_t limit = str.size()-( i > j ? i : j );
for (size_t k = 0; k < limit; ++k) {
if (str[i + k] != str[j + k]) break;
if (k > max_size) {
max_size = k;
max_pos = j;
}
}
}
max_array = max_size;
pos_array = max_pos;
}
}
SubStringFinder(string &s, size_t *m, size_t *p) :
str(s), max_array(m), pos_array(p) { }
};

int main(int argc, char *argv[]) {


string str = { string("a"), string("b") };
for (size_t i = 2; i < N; ++i) str = str[i-1]+str[i-2];
string &to_scan = str[N-1];

size_t *max = new size_t[to_scan.size()];
size_t *pos = new size_t[to_scan.size()];

parallel_for(blocked_range(0, to_scan.size(), 100),
SubStringFinder( to_scan, max, pos ) );

for (size_t i = 0; i < to_scan.size(); ++i)
cout << " " << (int)max << "(" << (int)pos << ")" << endl;
delete[] max;
delete[] pos;
return 0;
}

0 Kudos
2 Replies
yingemmachen
Beginner
52 Views

Hi,

I found a way to get around the problem. Just pass one dimensional arrays and convert them to two dimensional arrays later.

Ying
jimdempseyatthecove
Black Belt
52 Views

Usualy you iterate on the row index.