In software (as in real life) a lock is a device that controls access to a resource. Here’s an example. Suppose you’re running two programs that both want to print something. Only one of these programs at a time should be able to access the printer — you don’t want two documents spewing forth at once. One program acquires a lock on the printer. Until it releases the lock, the other program must wait. The lock helps these two programs control access to the shared resource (the printer).
The lock I’ve described is called a mutual exclusion lock or mutex because when one program acquires the lock, the other is made to wait, and vice versa. This kind of lock is great if the resource should be used by only one program at a time, but what if two programs should be allowed to use the resource simultaneously? What if there is some other rule for using the resource?
Let’s motivate this abstract question with a real-world example. In my apartment, I have a bathroom and a bedroom, which doubles as my office. It’s almost always the case that only one person at a time should be able to use the bathroom. I’d be comfortable installing a mutual exclusion lock on the bathroom door — one that locks automatically when a person enters and doesn’t unlock until he exits. But my bedroom/office is a different story. When I’m working or surfing the Internet, I don’t mind if others come into the room, but if I’m changing clothes or, um, sleeping, I don’t want anyone coming in. I need a different kind of lock.
The rule for access to the bedroom/office depends on how I’m using it. When it’s used as a bedroom, I need exclusive access. When it’s used as an office, I don’t. In software, this rule is represented by a lock called a read/write lock. Unlike a mutex, a read/write lock defines two modes of access: reading and writing. When a program acquires the lock, it also states which mode of access it requires. The lock permits many concurrent readers, but a writer must wait for all other readers and writers to release the lock. Reading is like surfing the Internet; writing is like changing clothes.
I’ve been programming a lot in Ruby lately. Ruby includes a mutual exclusion lock, but I couldn’t find a read/write lock, so I wrote one. Here are the code and tests. Enjoy!
{ 2 } Comments
“Reading is like surfing the Internet; writing is like changing clothes.”
Depends on what kind of surfing you’re doing
sync stdlib:
http://ruby-doc.org/stdlib/libdoc/sync/rdoc/index.html
Post a Comment