Here’s how I do it (in this case to make thread-safe calls to fftw, which are not thread-safe):
Declare a static (global) mutex object:
std::mutex myMutex;
In your context that can be called in multiple threads:
void Foo::myThreadSafeMethod( const ..., const ..., const...) const
{
std::unique_lock<std::mutex> lck (myMutex, std::defer_lock);
(thread safe code)
for( ... )
{
(thread safe code)
//calls to fftw are not thread safe
lck.lock(); //
index out_fft_size = M / 2 + 1;
fftw_array_raw out_fft
= (fftw_complex *)fftw_malloc(sizeof(fftw_complex) * out_fft_size);
fftw_plan p_fft;
p_fft = fftw_plan_dft_r2c_1d(M, in, out_fft, FFTW_ESTIMATE_PATIENT);
fftw_execute(p_fft);
fftw_destroy_plan(p_fft);
out.set_data(out_fft, M / 2 + 1);
lck.unlock(); //
(thread safe code)
}
}
I hope this helps,
Paulo