Can compiled reorder operations when std::scoped_lock is used inside new scope

94 Views Asked by At

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.

0

There are 0 best solutions below