While I was practicing lock-based vs. lock-free concurrency, I realised that my lock-based function takes less time than a function with no synchronisation:
// A simple money transfer function
void transfer(unsigned int from, unsigned int to, unsigned int amount)
{
lock_guard<mutex> lock(m); // removing this line makes it run slower!
accounts[from] -= amount;
accounts[to] += amount;
}
Here is the coliru link of the full code. What might be the reason?
Note: I am aware of the data-race issue!
UPDATE: My observation was just based on Coliru. So I run the same code on a MacBook Pro (Retina, Mid 2012) 2,6 GHz Intel Core i7 16 GB 1600 MHz DDR3 and realised that no-locking one runs twice faster than the lock-based one. But the lock-based one runs a little bit faster on Coliru consistently.