user3758015
user3758015

Reputation: 139

lock vs (try_lock, sleep, repeat) performance

I am updating some code and I came across several mutexs that were using the lines:

while (!mutex_.try_lock())
    sleep_for(milliseconds(1));

instead of just locking the mutex straight away:

mutex_.lock();

Is there any performance difference positive or negative to using the try lock and sleep approach vs straight locking the mutex or is it just wasted instructions?

Upvotes: 6

Views: 8731

Answers (1)

harmic
harmic

Reputation: 30597

lock() will block if the lock is not available, while try_lock() returns straight away even if the lock is not available.

The first form polls the lock until it is available, which has a couple of disadvantages:

  1. Depending on the delay in the loop, there can be unnecessary latency. The lock might become available just after the try_lock attempt, but your process still waits for the preset delay.

  2. It is a waste of CPU cycles polling the lock

In general you should only use try_lock if there is something useful that the thread can do while it is waiting for the lock, in which case you would not want the thread to block waiting for the lock.

Another use case for try_lock would be to attempt locking with a timeout, so that if the lock did not become available within a certain time the program could abort.

cppreference says that:

lock() is usually not called directly: std::unique_lock and std::lock_guard are used to manage exclusive locking.

Using these classes may be more appropriate depending on the circumstances.

Upvotes: 8

Related Questions