0

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.

Benji Mizrahi
  • 2,154
  • 2
  • 23
  • 38
  • How many threads are at play and what kind of system are you running this on? Please provide the CPU ID if possible. – KalyanS May 31 '15 at 19:14
  • 4
    "lock free" has specific meanings in concurrency, and does not refer to "code that executes undefined behavior due to lack of locks" like the above. See [wikipedia](https://en.wikipedia.org/wiki/Non-blocking_algorithm). – Yakk - Adam Nevraumont May 31 '15 at 19:29
  • Thanks, I used 'no-locking' instead. – Benji Mizrahi May 31 '15 at 19:32
  • 1. You are also measuring the printing, the thread creation overhead, and pretty much everything else under the sun. 2. Concurrently calling `get_rand()` from multiple threads is UB because you are racing on the engine. – T.C. May 31 '15 at 20:09
  • The code may not take the same time for each run. Profiling it for a some time gives better picture regarding how much time is spent on average on a function. – Nipun Talukdar Jun 01 '15 at 04:43
  • I took out all the logging and averaged multiple runs. The cpu times were very close; no-locking one was slightly faster – Benji Mizrahi Jun 01 '15 at 18:01

0 Answers0