Reputation: 43
My question concerns OpenMP critical sections in classes called by a parallellized for-loop which is not part of the same class as the critical section(s). Can critical sections be used this way?
Here is an example:
class TestFunction
{
TestFunction( SomeSharedObject& _obj) : obj_(_obj) {}
public:
void possibly_change_sharedobj( )
{
#pragma omp critical(myCriticalSection)
{
obj_.do_something();
}
}
SomeSharedobject& obj_;
};
class ClassWithParallelloop
{
void parallelloop()
{
#pragma omp parallel for
for( int i = 0; i < N; ++i)
{
TestFunction testfn( myobj_);
testfn.possibly_change_sharedobj();
}
}
SomeSharedObject myobj_;
};
Q: is the shared object (myobj_) protected against concurrent changes?
Upvotes: 1
Views: 727
Reputation: 393467
No, myobj_
is not "protected against concurrent changes", because that's not what critical sections do.
What they do, is prevent code in those sections from running simultaneously. So, as long as you guarantee that no code outside the critical section(s)* access myobj_
, you'll have prevented concurrent access (this is implicit protection).
Answering the other question: It is not a problem (not even relevant) that the omp ciritical
pragma is not inside the omp parallel
section, lexically.
Upvotes: 1