The volatile keyword and the RAII idiom (C ++)

assuming there is a class to control concurrent access to a (critical) block of code like this:

class RAIIObj : public boost::noncopyable {
public:
    explicit RAIIObj( LockObj& Obj ) : LkObj( Obj ) { Obj.Acquire(); }
    ~RAIIObj() { try { Obj.Release(); } catch (...) {} }
private:
    LockObj& LkObj;
};

When using this part of the code, do I need to use the volatile keyword to order not to see the code optimized?

For example, I need to write

ALockingObj LockObj;

void AFunc() {
    RAIIObj LKGuard( LockObj );

    // do some MT stuff
}

or

ALockingObj LockObj;

void AFunc() {
    volatile RAIIObj LKGuard( LockObj );

    // do some MT stuff
}

to make sure LKGuard always exists?

Since LKGuard is a local variable that is not used at any point in the body of the function, can it be optimized if I do not use the volatile keyword?

thank

+4
source share
2 answers

, . , lkobj , ( int lkobj;, )

+6

, pm100, , , GCC 4.9 RAII ( : -Os -flto). , , :

class MutexLocker
{
    chibios_rt::Mutex& mutex_;
public:
    MutexLocker(chibios_rt::Mutex& m) : mutex_(m)
    {
        mutex_.lock();
    }
    ~MutexLocker()
    {
        mutex_.unlock();
    }
};

volatile :

namespace impl_
{
    class MutexLockerImpl
    {
        chibios_rt::Mutex& mutex_;
    public:
        MutexLockerImpl(chibios_rt::Mutex& m) : mutex_(m)
        {
            mutex_.lock();
        }
        ~MutexLockerImpl()
        {
            mutex_.unlock();
        }
    };
}
using MutexLocker = volatile impl_::MutexLockerImpl;

, , , RAII volatile, .

0

All Articles