What is the reason for “locks are an expensive operation” to be uttered so often?

前端 未结 5 2113
野趣味
野趣味 2021-02-08 01:18

I have read a lot of material on threading, and all the synchronization mechanisms involved. I also understand the dangers of not doing it properly.

I just watched th

5条回答
  •  萌比男神i
    2021-02-08 01:39

    The short answer is: No, they're not expensive.

    The longer answer is: Yes, they're expensive because unless your locks are pointless and do nothing, the presence of locks will slow down your code.

    The actual answer requires a clarification:

    Technical vs. Implementation vs. Design:

    Technical: David Schwartz answer clarifies that technically the locks do not slow down code. That is, if you run single threaded code with lock statements in it the locks will not slow you down.*

    Implementation: Mark Ransom points out in his answer that locks are slow because the blocks cause delays which lead to a slower app.

    Design: The real answer is that a design which includes locks tends to be slower than designs which don't. Locks are designed to slow down your code.

    So, if you can reasonably manage to write code where the locks are never hit or not even needed, you absolutely should. That is why people say "locks are expensive." It is not that the lock(obj) statement is expensive, it is that the act of blocking other threads is expensive, and should only be undertaken in situations where you've evaluated that it is worth the expense.

    *Of course, if you get lock contention in a single threaded app, it will never finish.

提交回复
热议问题