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

前端 未结 5 2145
野趣味
野趣味 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条回答
  •  眼角桃花
    2021-02-08 01:51

    Is it the fact that it causes a LOCK# instruction to be emitted at Assembler level?

    No, since it doesn't always do that.

    Is it the fact that obtaining a lock requires a kernel call into the OS?

    No, since it typically doesn't do that.

    In fact, locks are very, very inexpensive. It's contention that's expensive. If you have to choose between a lock and contention, most of the time the lock is a better option.

    Locks, when used properly, are a contention avoidance mechanism. They automatically find threads that contend and de-schedule them such that one winds up primarily with threads that do not contend running concurrently.

    For example: Say you have four threads that are ready to run, A, B, C, and D. Say A and B contend with each other (say they manipulate the same collection). And say C and D contend with each other, but A doesn't contend with C. If A and B are running at the same time (contending), the locks will cause one of them to not be ready to run, the scheduler will then schedule C (or D), and the two threads will run without further contention. (At least until the next context switch.)

    Usually, when people say "locks are expensive", they mean that contention is expensive. Unfortunately, by phrasing it the way they do, they often encourage people to minimize locks but increase contention in the process. That is a losing proposition in the vast majority of cases. (There are a few exceptions.)

提交回复
热议问题