Information Technology Reference
In-Depth Information
5.6.7
Implementation best practices:
Writing simple, safe code with shared objects
Above we described the basic thought process you will follow when including
and using locks and condition variables in a shared object. To make things more
concrete, this section describes five simple rules that we strongly advocate as a
set of best practices for writing code for shared objects.
Consistent structure. At the core of many of these rules is a simple princi-
ple: follow a consistent structure. This is a meta-rule that underlies the other
rules. Although programming with a clean, consistent structure is always use-
ful, it is particularly important to strictly follow tried and true design patterns
for shared objects.
At a minimum, even if one way is not better than another, following the
same strategy every time (a) frees you to focus on the core problem because
the details of the standard approach become a habit and (b) makes it easier for
the people who follow you and have to review, maintain, or debug your code
understand your code. (Of course, often the person that has to debug the code
is you!)
As an analogy, electricians follow standards for the colors of wire they use
for different tasks. White is neutral. Black or red is hot. Copper is ground.
An electrician doesn't have to decide \Hm. I have a bit more white on my
belt today than black, should I use white or black for my grounds?" When an
electrician walks into a room she wired last month, she doesn't have to spend
2 minutes trying to remember which color is which. If an electrician walks into
a room she has never seen before, she can immediately figure out what the
wiring is doing (without having to trace it back into the switchboard.) Similar
advantages apply to following coding standards.
However, for concurrency programs, the evidence is that in fact the abstrac-
tions we describe are better than almost all others. Until you become a very
experienced concurrent programmer, you should take advantage of the hard-won
experience of those that have come before you. Once you are a concurrency guru,
you are welcome to invent a better mousetrap.
Sure, you can cut corners and occasionally save a line or two of typing by
departing from the standards, but you'll have to spend a few minutes thinking
to convince yourself that you are right on a case-by-case basis (and another few
minutes typing comments to convince the next person to look at the code that
you're right), and a few hours or weeks tracking down bugs when you're wrong.
It's just not worth it.
Five rules. These five rules are designed to help you avoid common pitfalls
we see in multi-threaded code from students and experienced programmers.
Search WWH ::




Custom Search