0

Is it possible that compiler can reorder operations before and after the lock, when locking is done in new scope?

For example:

std::cout << "started from ...
std::cout << "exited from ...
locking

or:

locking
std::cout << "started from ...
std::cout << "exited from ...

Full example code:

#include <iostream>
#include <thread>
#include <mutex>

std::mutex mtx;
int counter = 0;
bool updated = false;

void foo()
{    
    std::cout << "started from : " << std::this_thread::get_id() << std::endl;
    //or any other operation before locking

    {
    //explicit scope
    std::scoped_lock lk{mtx};
        if(counter++)
            updated = true;

    std::cout << "ctr: " << counter << std::endl;        
    std::cout << "upd: " << updated << std::endl;
    std::cout << "performed from : " << std::this_thread::get_id() << std::endl;
    }

    std::cout << "exited from : " << std::this_thread::get_id() << std::endl;
    //or any other operation after releasing lock
}

int main()
{
    std::thread t1(foo);
    std::thread t2(foo);

    t1.join();
    t2.join();
}

the output was so far stable:

started from : 140096075392768
ctr: 1
upd: 0
performed from : 140096075392768
exited from : 140096075392768
started from : 140096083785472
ctr: 2
upd: 1
performed from : 140096083785472
exited from : 140096083785472

but is there any guarantee that it will remain stable?

Is it possible to get the following output:

started from : 140096075392768 
exited from : 140096075392768
ctr: 1 
upd: 0 
performed from : 140096075392768 
ctr: 2 
upd: 1 
performed from : 140096083785472 
started from : 140096083785472 
exited from : 140096083785472 

So that in both threads the operations under the lock are reordered with the unsynchronized operations.

pidgun
  • 113
  • 6
  • Such reording would fail *as-if* rule I believe? Compiler is only allowed to change things if the result will be the same as the result of code written by you (assuming no UB occurs) – Yksisarvinen Aug 01 '19 at 14:31
  • related/dupe: https://stackoverflow.com/questions/37683493/how-compiler-like-gcc-implement-acquire-release-semantics-for-stdmutex – NathanOliver Aug 01 '19 at 14:31
  • Can you be more specific? If you state a particular output, we can tell you whether or not it's possible that this program would produce it. – Brian Bi Aug 01 '19 at 16:10
  • Edited a question, added an output which visualizes the question. – pidgun Aug 02 '19 at 07:23

0 Answers0