Performance consequence of volatile member functions

I found a 2001 article on Dr Dobbs: volatile - Multithreaded Programmer's Best Friend. I've always found 'volatile' somewhat useless - at least as a qualifier on variables - as access to variables shared between threads always go through some kind of library layer anyway.

Nonetheless, marking class instances, and methods, as 'volatile' to indicate their degree of thread safety as presented in the article seems very compelling.

To summarize the article quickly, the core idea is could declare a class like this:

struct SomeObject {
  void SingleThreadedMethod();
  void Method();
  void Method() volatile;
};

And then, instances of the class, like this:

// An object that will only be accessed from a single thread.
SomeObject singleThreaded;
// An objecect that will be accessed from multiple threads.
volatile SomeObject sharedObject;

sharedObject.SingleThreadedMethod(); //this will be an compile error
sharedObject.Method(); // will call the volatile overload of Method
singleThreaded.Method(); // would call the non volatile overload of Method.

The idea being that methods like "Method() volatile" would be implemented:

void SomeObject::Method() volatile {
  enter_critical_section();
  const_cast(this)->Method();
  leave_critical_Section();
}

Obviously smart pointers can automate the atomic-lock-and-cast-to-non-volatile process - the point is that the volatile qualifier can be used, in its intended usage, to mark class members and instances to indicate how they're going to be used from multiple threads and hence get the compiler to either tell the developer when single threaded (non volatile) methods are being called on a volatile object, or even to pick the threadsafe version automatically.

My question about this approach is: What are the performance implications of 'volatile' qualified methods? Is the compiler forced to assume that all variables accessed in a volatile function need to be treated as volatile and thus excluded from optimization opportunities? Will local variables be excluded from optimization? That could be a big performance drag on any volatile qualified member function if so.

18
задан Chris Becke 13 December 2010 в 11:54
поделиться