einfaches OpenMP-Beispiel



  • Ich wollte mir mal OpenMP anschauen und habe einfach mal ein kleines Beispiel kopiert:

    #include <iostream>
    #include <omp.h>
    
    int main(int argc, const char **argv)
    {
        #pragma omp parallel
        {
            int nloops = 0;
    
            #pragma omp for 
            for (int i=0; i<1000000; ++i)
            {
                ++nloops;
            }
    
            int thread_id = omp_get_thread_num();
    
            std::cout << "Thread " << thread_id << " performed "
                      << nloops << " iterations of the loop.\n";
        }
    
        return 0;
    }
    

    Mein Output:

    Thread Thread Thread Thread 910 performed 833336Thread performed 83333 iterations of the loop.
    Thread 0 performed 83334 iterations of the loop.
    Thread 3 performed 83334 iterations of the loop.
    iterations of the loop.
    performed 83333 iterations of the loop.
    Thread 2 performed 83334 iterations of the loop.
    Thread 4 performed 83333 iterations of the loop.
    11 performed 83333 iterations of the loop.
    7 performed 83333 iterations of the loop.
    Thread 1 performed 83334 iterations of the loop.
    Thread 8 performed 83333 iterations of the loop.
    Thread 5 performed 83333 iterations of the loop.

    Ich verstehe nicht so ganz, warum das nicht funktioniert.



  • Deine Ausgabe ist nicht threadsafe, die Threads interrupten sich gegenseitig und schreiben dann selber etwas. Du brauchst eine Mutex.



  • SLx64 schrieb:

    Ich wollte mir mal OpenMP anschauen

    OpenMP ist nicht mehr zeitgemäss. Nimm lieber TBB oder so.



  • Ah okay danke! 😉


Anmelden zum Antworten