Having read Can mutex implementations be interchanged (independently of the thread implementation), it is my understanding that I can ensure that my class is thread safe for all thread implementations, by using C++ 11 mutexes.
Am I correct in my understanding? I am expecting either yes (perhaps with caveats) or no (with reasons).
- My code may need recompilation on the target platform, but no changes are needed to my source code. (@Peter)
- Alternatively stated, I ought to be able to compile for a particular platform and deliver a .so that can be safely used with any thread library?
Given the down voting, I will try to be more precise.
Is the C++11 implementation of mutexes independent of any other thread API? Do C++11 mutexes only know about each other and implement blocking independently of how the thread of execution reached that point.
Will a C++11 mutex always work with OpenMP (with recompilation) ? Can Team A deliver a thread safe API (using C++ mutexes) for use by Team B, regardless of the particular thread API used by Team B? All code can be recompiled.
I am attaching a working example.
#include <iostream>
#include <omp.h>
#include <mutex>
class A {
unsigned n = 0;
public:
void inc() {
++n;
}
unsigned get() {
return n;
}
};
class B {
std::mutex mutex;
unsigned n = 0;
public:
void inc() {
mutex.lock();
++n;
mutex.unlock();
}
unsigned get() {
return n;
}
};
int main() {
A a;
B b;
#pragma omp parallel for
for (int i = 0; i < 100000; i++) {
a.inc();
b.inc();
}
std::cout << a.get() << " " << b.get() << std::endl;
}
The output of my last run was:
98015 100000
Is this by luck or design?