The Quantum Physicist
The Quantum Physicist

Reputation: 26356

C++: OpenMP: Copying function pointers for multithreading

I have a parallelized fitting program (parallelized with OpenMP) that takes the function that it has to fit using function pointers. I've been facing problems, and eventually I found out that I pass the same function pointer to the class that does the fitting, which conflicts with the others and produces messy results.

How can I "copy" function pointers to make them thread-safe, or in other words, to have threads not conflict with each other?

The function I'm pointing too looks like this:

void function(const Real t, RealArray &a, Real &y)
{
#pragma omp critical //if I remove this line, the catastrophe happens and I get wrong results
    {
    if(t < FIDLength)
    {
        y = ...;
    }
}

And the class in each thread is constructed as follows:

FitClass fit(DSxAxis1.size(),initialValues_param.size(),function,function2,constraints3D);

function and function2 are function pointers. They both are used the same way.

Thank you.

Upvotes: 0

Views: 702

Answers (1)

The Quantum Physicist
The Quantum Physicist

Reputation: 26356

I used a semi-functor and it worked. So my fitting class has now a template parameter that contains the function, its derivatives and other stuff. And this worked properly.

Result: Not all std functions are thread-safe.

Upvotes: 1

Related Questions