简体   繁体   中英

volatile keyword and RAII idiom (C++)

assuming to have a class to control concurrent access to a (critical) code block similar to this one:

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

When using such piece of code, do I need to use volatile keyword in order not to see the code be optimized away?

For example, do I have 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
}

in order to be sure that LKGuard always exists?

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

Thanks

no you dont need to declare it volatile. The compiler can see that instantiating lkobj does a whole bunch of stuff that cant be optimized out (as opposed to int lkobj; which clearly does nothing)

While the answer provided by pm100 is indeed correct as far as the standard is concerned, I discovered that GCC 4.9 can optimize RAII types away (optimization flags: -Os -flto ). This is the code I had that the optimizer was throwing away:

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

Making the type volatile solved the problem:

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;

Therefore, despite the fact that the standard does not require that, I would suggest to explicitly declare RAII types volatile in order to account for aggressive optimization.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM