Hi,

I have a problem understanding what is going on in this code:

#include <iostream>
#include <omp.h>
using namespace std;


class A
{
public:
    A()
    {
        cout<<"A created"<<endl;
    };

    ~A()
    {
        cout << "A destroyed" << endl;
    }

    void printA( void )
    {

    cout<<"ok"<<endl;
    }
};



int main()
{
    A a;
#pragma omp parallel num_threads(omp_get_max_threads())  firstprivate(a)
    {
        cout << "thread ID: " << omp_get_thread_num() << endl;
#pragma omp for schedule(static,1)
    for ( int i = 0; i< 10; i++)
    {
        cout << "i: " << i << endl;
        a.printA();
    }
    }
    system("pause");
    return 0;
}

basically the code runs in parallel fine but what i can't understand that I get a message that A is created only one time while I get the message that A is destroyed multiple times according to my threads number. While if I changed firstprivate to private I get the message that A is created multiple times too!
My question is why?

Thanks.

Recommended Answers

All 2 Replies

You're monitoring the default constructor, which is being used once. You're not monitoring the copy constructor as well. Add this to your class to see it:

 A( const A& other )
 { 
   cout<<"A copied"<<endl;
 }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.