2.14.7. thread_shlckstry

[<<<] [>>>]

@c Shared locks

The following functions implement shared locking. These functions do not call system dependant functions. These are built on the top of the MUTEX locking functions.

A shareable lock can be @b{READ} locked and @b{WRITE} locked. When a shareable lock is READ locked another thread can also read lock the lock.

On the other hand a write lock is exclusive. A write lock can appear when there is no read lock on a shareable lock and not write lock either.

@cr

The story to understand the workings:

Imagine a reading room with several books. You can get into the room through a small entrance room, which is dark. To get in you have to switch on the light. The reading room has a light and a switch as well. You are not expected to read in the dark. The reading room is very large with several shelves that easily hide the absent minded readers and therefore the readers can not easily decide upon leaving if they are the last or not. This actually led locking up late readers in the dark or the opposite: lights running all the night.

To avoid this situation the library placed a box in the entrance room where each reader entering the room have to place his reader Id card. When they leave they remove the card. The first reader coming switches the light on, and the last one switches the light off. Coming first and leaving last is easily determined looking at the box after dropping the card or after taking the card out. If there is a single card after dropping the reader card into you are the first coming and if there is no card in it you took your one then you are the last.

To avoid quarreling and to save up energy the readers must switch on the light of the entrance room when they come into and should switch it off when they leave. However they have to do it only when they go into the reading room, but not when leaving. When someone wants to switch a light on, but the light is already on he or she should wait until the light is switched off. (Yes, this is a MUTEX.)

When the librarian comes to maintain ensures that no one is inside, switches the light of the entrance room on, and then switches the reading room light on. If someone is still there he cannot switch the light on as it is already switched on. He waits until the light is switched off then he switches it on. When he has switched the light of the reading room on he switches the light of the entrance room off and does his job in the reading room. Upon leaving he switches off the light of the reading room.

Readers can easily enter through the narrow entrance room one after the other. They can also easily leave. When the librarian comes he can not enter until all readers leave the reading room. Before getting into the entrance room he has equal chance as any of the readers.


[<<<] [>>>]