Can mutex implementations be interchanged (indepen

2019-04-28 15:54发布

问题:

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;
};

回答1:

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.



回答2:

This link provides a useful discussion:

http://groups.google.com/group/comp.programming.threads/browse_thread/thread/67e7b9b9d6a4b7df?pli=1

Paraphrasing, (at least on Linux) Boost::Thread and OpenMP both an interface to pthread and so in principle should be able to be mixed (as Anders says +1), but mixing threading technologies in this way is generally a bad idea (as Andy says, +1).



回答3:

The part requiring compatibility is the thread suspension, rescheduling and context switching. As long as the threads are real threads, scheduled by the operating system, you should be able to use any mutex implementation that relies on some kind of kerner primitive for suspending and resuming a waiting thread.