In a conversation about concurrency and the C ++ 11 memory model, Herb Sutter gives examples of invalid optimizations.
http://channel9.msdn.com/Shows/Going+Deep/Cpp-and-Beyond-2012-Herb-Sutter-atomic-Weapons-2-of-2
From slide per minute 17:
void f(vector<widget>& v) {
if(v.length()>0) xMutex.lock();
for(int i = 0; i < v.length(); ++i)
++x;
if(v.length()>0) xMutex.unlock();
}
"A very likely (if deeply mistaken) transformation of the central loop:"
r1 = x;
for(int i = 0; i < v.length(); ++i)
++r1; // oops: write is not conditional
x = r1;
He explains: "... this record is not conditional, it will be executed at each execution, even if doOptionalWork is false, which will lead to a record of the record that is not protected by a mutex lock that introduces the race ..."
Why does he say that the invented record is not protected by a mutex lock? I realized that the complete conversion is described as follows.
void f(vector<widget>& v) {
if(v.length() > 0) xMutex.lock()
r1 = x;
for(int i = 0; i < v.length(); ++i)
++r1;
x = r1;
if(v.length() > 0) xMutex.unlock();
}
But this may be so.
void f(vector<widget>& v) {
if(v.length() > 0) xMutex.lock()
r1 = x;
for(int i = 0; i < v.length(); ++i)
++r1;
if(v.length() > 0) xMutex.unlock();
x = r1;
}
, 2 , 1. 1? , , x ?
" v.length() 0, ...", , . , .