What's the difference between an exclusive lock and a shared lock?

前端 未结 4 1348
终归单人心
终归单人心 2021-01-29 17:08

According to wikipedia,

Shared locks are sometimes called \"read locks\" and exclusive locks are sometimes called \"write locks\".

4条回答
  •  野的像风
    2021-01-29 17:59

    It's pretty straightforward. Read locks are also known as shared locks because more than one process can read at the same time. The point of a read lock is to prevent the acquisition of a write lock by another process. By contrast, a write lock inhibits all other operations while a write operation completes which is why it is described as exclusive.

    So a read lock says "you can read now but if you want to write you'll have to wait" whereas a write lock says "you'll have to wait".


    I realise you're researching in support of your studies, but I can't resist the urge to lecture.

    Incompetent use of locking is a primary cause of performance headaches. Use of a locking system that differentiates read and write locks is a good start, but careful design can sometimes eliminate much of the need to lock. For example, session state should never be held in one global collection per element of state.

    I have actually seen this done. It's an atrocious design, causing boxing and a change to a collection for every last change to session state, entailing a protracted write lock. Overheads were crippling, effectively reducing the server to single threaded behaviour.

    Simply aggregating all the session state into a struct was a huge improvement. Changes to session state merely changed the values of members of a session's state struct. Since no other session had occasion or even opportunity to directly reference a session's state, the only collection being updated was the list of sessions. As a result, locking was completely unnecessary during a sesssion, only at the start and end, and throughput rose by a factor of 3000.

    The other common locking scenario is resources shared between threads of a user application. Most modern frameworks address this using messages rather than locks; when you "transition to the UI thread" you are actually queueing a message containing a function pointer and some parameters (or a delegate and a stack frame depending on implementation).

提交回复
热议问题