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

前端 未结 4 1347
终归单人心
终归单人心 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 18:04

    I wrote this answer down because I thought this would be a fun (and fitting) analogy:

    Think of a lockable object as a blackboard (lockable) in a class room containing a teacher (writer) and many students (readers).

    While a teacher is writing something (exclusive lock) on the board:

    1. Nobody can read it, because it's still being written, and she's blocking your view => If an object is exclusively locked, shared locks cannot be obtained.

    2. Other teachers won't come up and start writing either, or the board becomes unreadable, and confuses students => If an object is exclusively locked, other exclusive locks cannot be obtained.

    When the students are reading (shared locks) what is on the board:

    1. They all can read what is on it, together => Multiple shared locks can co-exist.

    2. The teacher waits for them to finish reading before she clears the board to write more => If one or more shared locks already exist, exclusive locks cannot be obtained.

提交回复
热议问题