Do all mutex implementations ultimately call the same basic system/hardware calls – meaning that they can be interchanged?
Specifically, if I’m using __gnu_parallel algorithms (that uses openmp) and I want to make the classes they call threadsafe may I use boost::mutex for the locking? or must I write my own mutex such as the one described here
//An openmp mutex. Can this be replaced with boost::mutex?
class Mutex {
public:
Mutex() { omp_init_lock(&_mutex); }
~Mutex() { omp_destroy_lock(&_mutex); }
void lock() { omp_set_lock(&_mutex); }
void unlock() { omp_unset_lock(&_mutex); }
private:
omp_lock_t _mutex;
};
Edit, the link above to the openmp mutex seems to be broken, for anyone interested, the lock that goes with this mutex is along these lines
class Lock
{
public:
Lock(Mutex& mutex)
: m_mutex(mutex),
m_release(false)
{
m_mutex.lock();
}
~Lock()
{
if (!m_release)
m_mutex.unlock();
}
bool operator() const
{
return !m_release;
}
void release()
{
if (!m_release)
{
m_release = true;
m_mutex.unlock();
}
}
private:
Mutex& m_mutex;
bool m_release;
};
You should not mix synchronization mechanisms. E.g. current pthreads mutex implementation is based on futex and it is different from previous pthreads implementations (see
man 7 pthreads). If you create your own level of abstraction, you should use it. It should be considered what is your need – inter-thread or inter-process synchronization?If you need cooperation with code that uses boost::mutex, you should use boost::mutex in place of open mp.
Additionally IMHO it is quite strange to use open mp library functions to realize mutex.