I need to run a cycle n times, with one cycle run being equal to one experiment, i.e. just some tally of information.

for(int k = 0; k < N; ++k){ xo = 0 + rand()%w; yo = 0 + rand()%h; cout << calc() << endl; // выводим результат подсчета } 

The calc function considers my average pixel brightness in an image with coordinates xo, yo and given w, h.

At the same time, my data is loaded outside the loop and written to my copy of the Image class. When trying to write a directive

 omp_set_num_threads(4); #pragma omp parallel for 

everything counts for me, everything will figure out the correct values, some kind of garbage, and then an error message.

Could the error be that I work with the same class instance in each thread? Those. for the first stream - I ask to calculate the average of the image with the coordinates (x1, y1), as a result, my Image class arr field already contains data for these coordinates, and right there I ask to calculate the average for other coordinates. If there is an error in this, then how can paralleling be a process?

  • Yes, the logical mistake is that you are trying to work with one object in different threads. But the program crashes is not quite for this reason. First, if I correctly understood the essence of the problem, then you must first make an array of objects that will be processed by these streams. Secondly, remove cout from the loop — I / O operations are very slow and they will interfere with work (and generally, cout cannot be used here without synchronization). Output all results after the parallel section. Thirdly, you in the pragma must also correctly define the roles of variables: who is common for everyone to be inclined, etc. - Vladimir
  • In addition, rand () is not the best option to run in different threads at the same time - it is not thread safe, as I understand it. If you use C ++ 11, it may be better to use its generators (from STL) - a separate generator for each stream (but this is in theory. I myself have not tried their behavior with OpenMP yet). - Vladimir
  • @Vladimir Ie, as I understood, I need to create an array of class instances? - TaraniH
  • On this part of the code it is very difficult to understand what is really needed. xo,yo, calc() are members of a class and this loop is inside a class? If so, then most likely, you will have to do an array of objects, and do a loop outside the methods of the class. If these are just separate variables and the calc() function is a normal function, then you have big problems: on the call to calc() I assume that xo and yo are global variables - and this is a problem for OpenMP (because it turns out that all threads try to write in one cell). - Vladimir

0