Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.


Channels ▼
RSS

Conversations: To Sleep, Perchance


April 2002 C++ Experts Forum/Conversations


Copyright 2002, Jim Hyslop and Herb Sutter

I had been awake late all week and over the weekend, being "interviewed" by my captors. I was definitely beginning to dislike my new situation, but I had to admit it could have been worse. Much worse. I thought of those who had been chewed up by the Goofies in the other world, beyond the Ballroom gate that had been our last refuge.

I shivered slightly in the cold, dank room. The front of the metal chair's seat dug into my legs. I shifted to find a less uncomfortable position.

"What are those portals? What do you know about the alien devices?" my interrogator asked again, his accent not as heavy as some of the others'. I kept answering as well as I could, though I knew little. But the same questions came, again, again: "What orders were you given? How were your officers planning to use the alien technology? When did you—?"

The hours were long, the days longer. During that time I never did see another face from my own unit for longer than a moment, only an occasional silent furtive glance we shared as we passed each other in the corridors, being led by our captors to or from interrogation rooms.


I had been working late all week and over the weekend, rushing to meet the project deadline. I was definitely beginning to dislike our new manager's style of "to-do lists." Not even triple helpings of the caffeinated drink stuff masquerading as coffee in the lunchroom could keep me awake.

"Hey, Junior, what's with your latest code checkin?" My head jerked upright at the sudden voice. Great. Just what I needed — a visit from Bob. Bob, the anti-Guru. How I'd like to... I broke off that train of thought. He wasn't worth facing criminal charges over. I sighed, forced my eyes open, and turned to him.

"I don't suppose you'd care to clarify that, would you?" I asked. I didn't care how testy I sounded. Nuts with diplomacy — I was tired.

Bob didn't seem to notice though. "That code you checked in. It's unreadable, man." He sloshed his cup and chuckled annoyingly. "Those ostream insertion operators getting in the way of your caffeine stream, kid?"

I stared at Bob. My eyes began to bulge. This arrogant, incompetent, programmer-wannabe was daring to call my code unreadable? I sat for a few moments, allowing my anger to build up to a nice, full head of steam, so I could really vent on him. I think my cheek even began to twitch.

But then Wendy — back from her maternity leave — gophered up and barged in: "Hey, Bob, thanks for breaking the ice for me." (Wendy, being nice to Bob? I blinked. I began to wonder if I was dreaming.) "I had noticed the problem," she continued, "but couldn't think of a diplomatic way of saying it. I'll go over the code with him."

Then I understood — Wendy didn't want me facing criminal charges, either.

"Hey, no problem, babe," Bob said, sipping on his latte as he left. Wendy's eyes narrowed.

It was then that I heard the snap. I thought Wendy had torn a chunk of her cubicle wall off, but then I heard a yelp from Bob. I turned, and he was rubbing the back of his neck. A large elastic band lay on the floor at his feet.

"Is something wrong, my colleague?" I jumped at the Guru's gentle voice. As always, she had appeared unannounced, silently, and with a thick tome in hand. It looked old, and I didn't recognize the cover. Bob glowered at the three of us a moment, trying to figure out who had shot the elastic. Then he picked up his latte cup and stormed off.

"Nice shootin', Sheriff," I drawled.

"I used to pick off flies at thirty paces," the Guru replied as she retrieved the elastic. She placed it in her book, using it as a bookmark as the tome closed.

"Y'know, Bob did have a point," Wendy said. I glanced up at her. She was wiping tears of laughter from her eyes.

"Yeah," I quipped, "but if he combs his hair right and wears a hat, maybe no one will notice." That set Wendy off into gales of laughter, and she sank out of sight into her cubicle.

"My young apprentice," the Guru walked — glided, rather — toward me. I sobered up — Bob was not around, yet she was still in her Guru act; this did not bode well for me. "Have you reviewed the code you checked in last night?"

I turned to my keyboard and called up the file I had worked on. "Oh, my," I said, after I read it:

class Car
{
public:
 explicit Car( list<Occupant>& );

private:
 virtual ostream&
   InsertIntoStream( ostream& ) const;

 friend ostream&
   operator<<( ostream&, const Car& );

 Mutex m_;

 // ...
};

ostream& operator<<( ostream& o, const Car& c )
{
 return c.InsertIntoStream(o);
}

ostream& 
Car::InsertIntoStream( ostream& traffic ) const
{
 Lock lock( m_ ); // acquire mutex, be thread-safe!

 string rep = MakeDelim( occupants_.begin(),
                         occupants_.end(),
                         "," );

 // Pre-conditions:
 // Is there room in the traffic for me?
 if( traffic.width() < rep.size()
     || accelerationLane.length() < 100 )
    throw TrafficTooHeavy();

 if( !DoShoulderCheck() ) {
    Sleep( 500 );
    Retry();
  }

  SignalLaneChange();
  traffic << rep;
  CancelSignal();

  if( CurrentSpeed() > SPEED_LIMIT * 1.3 )
    EaseOffGas();

  return traffic;
} // lock is released

"Indeed," the Guru said. "Would you care to explain this?"

"Uh, well," I hemmed and hawed, embarrassed. "As I recall, yesterday when I was driving to work, I got into the acceleration lane for the freeway..."

"And...?"

"Well, maybe I was feeling a little punchy. I noticed that the traffic on the freeway was quite heavy. Suddenly, I felt like I was no longer driving a car — I was a persistent object being inserted into a stream."

"And...?"

"You know, with the insertion operator. My shoulder check felt like a precondition, ready to throw an exception if there wasn't enough space for my car. Then I got onto the freeway itself and went through my post-conditions... I mean, checked my speed. I guess when I was working late last night, I was thinking about all that."

But she just shook her head. "No. That," she admonished, stern, "is not the problem of which I spoke."

"No?"

"No. This is abominable. You have misused the width member of ostream. The width has nothing to do with the amount of data that can be inserted. It has to do with...? Well?"

"Oh," I answered, deeply embarrassed. I don't know what disturbed me more: the Guru taking my weird story and addled thinking in stride; or the fact that she was still in her Guru act — something reserved for Bob and new interns. "The width is just the requested minimum width of the next piece of output. And even if my representation is longer than the width, it would still all be written out, so I don't need to worry about truncation."

"That," she continued, face severe, "was the first abomination. The second, like it, is this: You have also violated some of our blessed coding guidelines — vile magic numbers like 100 and 500 and 1.3."

"Oh. Okay, I'll fix it. That's not too major."

"That," she continued, face darkening, "was the second abomination. The third, like it, is this: Thou shalt not make objects thread-safe; it is a perversion. Thread safety is good, but now every Car in the system will incur the evil lock overhead whether that Car object is actually ever used by more than one thread or not. This was one of the mistakes in the early so-called 'thread-safe' Java containers. Those designers soon learned the errors of their ways. If an object can be used by multiple threads, it is the responsibility of the outside code that owns that object, and that code alone, to serialize all access to it. This too is encapsulation and a striving after correctness. I will not even comment on the related issues with Sleep."

"Sleep?" I asked, and immediately thought better of it, but it was too late.

"Sleep!" she thundered. "Waiting with a lock acquired and not released? When it is a fundamental law that long-term locks are anathema! Making a native system call in plain code, and not using the wrapper in our System module? When our standards require that all platform-specific calls must be isolated only in the System module, for portability! What do you think will happen when we port to Linux! Will he have to touch this module too! Why should we not just abandon all sense and litter our entire code base with such detritus! What will you do when—" She stopped, awkwardly, visibly controlled herself, and added, somewhat belatedly: "But I said I would not comment, and I will not."

I slouched further down in my seat, with no ready reply. I had rarely seen her this furious. Wendy explained to me later that the Guru was a bit out of sorts after having just had a personal fight with Bob, and indeed as it turned out later the Guru did become much nicer within a few days after that, so I suppose Wendy must have been right. At the time, it was a mystery to me.

The Guru looked at me darkly a few moments more and then relented somewhat. "I'm sorry," she said quietly, "it's just... well. At any rate, I shall refrain from commenting also on naming conventions that verge on the blasphemous. Please be more careful in the future. But none of those was your most serious error."

"I — I guess I wasn't thinking too clearly last night," I said lamely.

"You mean this morning," the Guru pointed at the timestamp of my checkin: Tuesday, April 2nd at 12:03 a.m. "That was your most serious error, I think. You meant well, and hard work is always appreciated, but there are times when working hard is not the same as working well. Explain to Wendy what you intended to do," she continued, "then go home and get some rest. No project is worth endangering one's health or family life." As she glided away, she opened her book and read softly, " 'We are such stuff as dreams are made on, and our little life is rounded with a sleep' [1]. "


It was some time, many days, before they were satisfied with my answers. That, or they saw there was nothing more to be got from me. The time finally came when I was transferred to another holding area for captives, this time outside the alien city and in the base above.

At least it was warmer there, and finally again I was with others of my unit. Best of all, there was Jeannine.

She brightened when she saw me and came right to me as the door clanged shut behind me. "You're alive! Where—?"

I put up a hand to fend her question off and muttered "later, love, later" as I stumbled to a free bunk and collapsed into black sleep.

Reference

[1] Wm. Shakespeare. The Tempest, Act IV, sc. i.

Jim Hyslop is a senior software designer at Leitch Technology International Inc. He can be reached at [email protected].

Herb Sutter (<www.gotw.ca>) is an independent consultant and one of the instructors of The C++ Seminar (<www.gotw.ca/cpp_seminar>). He is also secretary of the ISO/ANSI C++ standards committee and author of the acclaimed books Exceptional C++ and More Exceptional C++.


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.