0

I'm learning c++ and trying to make my own calculator with charting. In this part, when I try to fill an array with coordinates. I want to make it faster using multithreading. But when I did so, the code began to work much worse, slower. How can I solve the problem what am I doing wrong? By the way, it doesn't work at all without "#pragma omp critical"

    omp_set_num_threads(2);
    #pragma omp parallel for
    for (current = start; current < finish; current ++) {
        Calc b(a.get_string());
        double y_value = b.parsing((double)current/1000);
        #pragma omp critical
        {
            if (y_value > yL || y_value < yR) {
                x->push_back((double)current/1000);
                y->push_back(y_value);
            }
        }

x and y this is QVector. Please try to express yourself as simply as possible because I'm just learning. Thank you all very much!

1 Answers1

1

The critical section is certainly not needed because the condition y_value > yL || y_value < yR can be done in parallel assuming yL are yR left unmodified and because x and y can be initialized with the size finish-start and you can then perform direct accesses on the vector like x[current-start] = (double)current/1000;. Also, please note that it is probably better to put current private using the clause private(current) in the parallel directive.

Jérôme Richard
  • 41,678
  • 6
  • 29
  • 59
  • 1
    Since 'current' is the loop variable it is guaranteed by the OpenMP standard to be private – dreamcrash Jun 22 '22 at 13:13
  • @dreamcrash I am never sure about this though I read the specification many time (and now it start to be too be for a basic quick search :p), so thank you for clarifying this point. – Jérôme Richard Jun 22 '22 at 16:33
  • 1
    Yep, that used to be the case for me as well, but I got correct a few times by the expert Hristo Iliev. btw https://stackoverflow.com/a/67073601/1366871 shows the OpenMP reference. – dreamcrash Jun 22 '22 at 16:41
  • Thank you very much! I managed to do it thanks to you! – Genrih Frank Jun 23 '22 at 08:47
  • 1
    @GenrihFrank Great don't forget to make this answer as accepted. – dreamcrash Jun 23 '22 at 10:55