0

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.

2
Contributors
2
Replies
8
Views
3 Years
Discussion Span
Last Post by salah_saleh
1

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;
 }
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.