views:

26

answers:

1

On a mutex: I was asking about the performance of lock here and about the performance of try_lock here.

The question about try_lock was closed as exact duplicate to the one about lock. However, I fail to see why try_lock must behave in the same way as lock in every possible mutex implementation.

As this question was not really answered in the following discussion, I am putting it as a new question here:

Why is it like this? Is it because there is just one possible way you can implement try_lock? (I.e. the most natural way.)

A: 

The performance of try_lock on a given mutex is strongly tied to the implementation of lock. If locking the mutex always requires a system call then try_lock will likely also require a system call. On the other hand, if lock has a "fast path" that runs in user-space without a system call, then try_lock will likely have a similar implementation to that "fast path". In fact, a common implementation of lock is basically if(!try_lock()) lock_with_system_call().

Anthony Williams