Usability: Watch out for those non-errors that start with “ER”

Today I had a nice lesson in transaction codes. I did a happy little online transaction, and then the confirmation screen came up with what at first glance looked like an error. It startled me, until I read more closely:

Thank you. Your transaction has been placed and received by SuperMondoCorp.

Transaction Confirmation Number: ER6661234567

“Yikes!” thought I to myself, thought I. Then, “oh, the bolded confirmation number just starts with ER which only looks like ERR.” (And yes, the rest of the number did start with 666. I only altered the other numbers.)

I realize you can’t anticipate everything, but it is a reminder about usability. If the thing you draw the customer’s eye to on a confirmation screen can start with what looks like a negative confirmation, it’s not the greatest thing.

Effective Concurrency: Interrupt Politely

The latest Effective Concurrency column, “Interrupt Politely”, just went live on DDJ’s site, and will also appear in the print magazine. From the article:

ec10-tbl1 Violence isn’t the answer.

We want to be able to stop a running thread or task when we discover that we no longer need or want to finish it. As we saw in the last two columns, in a simple parallel search we can stop other workers once one finds a match, and when speculatively running two alternative algorithms to compute the same result we can stop the longer-running one once the first finds a result. [1,2] Stopping threads or tasks lets us reclaim their resources, including locks, and apply them to other work.

But how do you stop a thread or task you longer need or want? Table 1 summarizes the four main ways, and how they are supported on several major platforms. Let’s consider them in turn. …

I hope you enjoy it.
 
Finally, here are links to previous Effective Concurrency columns (based on the dates they hit the web, not the magazine print issue dates):
July 2007 The Pillars of Concurrency
August 2007 How Much Scalability Do You Have or Need?
September 2007 Use Critical Sections (Preferably Locks) to Eliminate Races
October 2007 Apply Critical Sections Consistently
November 2007 Avoid Calling Unknown Code While Inside a Critical Section
December 2007 Use Lock Hierarchies to Avoid Deadlock
January 2008 Break Amdahl’s Law!
February 2008 Going Superlinear
March 2008 Super Linearity and the Bigger Machine
April 2008 Interrupt Politely

Cringe not: Vectors are guaranteed to be contiguous

Andy Koenig is the expert’s expert, and I rarely disagree with him. And, well, when I do disagree I’m invariably wrong… but there’s a first time for everything, so I’ll take my chances one more time.

I completely agree with the overall sentiment of Andy’s blog entry today:

I spend a fair amount of time reading (and sometimes responding to) questions in the C++ newsgroups. Every once in a while, someone asks a question that makes me cringe.

What makes a question cringe-worthy?

Usually it is a question that implies that the person asking it is trying to do something inappropriate.

Asking how to violate programming-language abstractions is similar: If you have to ask, you probably shouldn’t be doing it.

Amen! Bravo! Absolutely correct. Great stuff. Except that the example in question isn’t violating an abstraction:

For example, I just saw one such question: Are the elements of a std::vector contiguous? Here is why that question made me cringe.

Every C++ container is part of an abstraction that includes several companion iterators. The normal way of accessing a container’s elements is through such an iterator.

I can think of only one reason why one should care whether the elements of a vector are in continuous memory, and that is if you intend to use pointers, rather than iterators, to access those elements. Doing so, of course, violates the abstraction.

There is nothing wrong per se with violating abstractions: As Robert Dewar told me more years ago than I care to remember, some programs are poorly designed on purpose. However, there is something wrong with violating abstractions when you know so little of the data structures used to implement those abstractions that you have to ask strangers on Usenet about your proposed violation. To put it more bluntly: If you have to ask whether vector elements are contiguous, you probably should not be trying to make use of that knowledge.

The reason this analysis isn’t quite fair is that contiguity is in fact part of the vector abstraction. It’s so important, in fact, that when it was discovered that the C++98 standard didn’t completely guarantee contiguity, the C++03 standard was amended to explicitly add the guarantee.

Why is it so important that vectors be contiguous? Because that’s what you need to guarantee that a vector is layout-compatible with a C array, and therefore we have no reason not to use vector as a superior and type-safe alternative to arrays even when we need to exchange data with C code. So vector is our gateway to other languages and most operating systems features, whose lingua franca is the venerable C array.

And it’s not just vector: The TR1 and C++0x std::array, which implements fixed-size arrays, is also guaranteed to be contiguous for the same reasons. (std::array is available in Boost and, ahem, the VC++ TR1 implementation we shipped today.)

So why do people continually ask whether the elements of a std::vector (or std::array) are stored contiguously? The most likely reason is that they want to know if they can cough up pointers to the internals to share the data, either to read or to write, with other code that deals in C arrays. That’s a valid use, and one important enough to guarantee in the standard.

Visual C++ 2008 Feature Pack now available

Back in November, I reported that we’d be shipping Visual C++ 2008 that month (we did!) and that we’d soon thereafter be doing the “agile thing” and shipping a major update mere months later, instead of waiting two years between releases per our prior tradition. I wrote:

The update is expected to be available in beta form in January 2008, and to ship in the first half of 2008. Enjoy!

Well, it’s official: It’s available. Enjoy! Besides major updates to MFC for the latest Office/VS/Vista look-and-feel to support first-class native code development, it also includes most of TR1 (everything except C99 compatibility, and the special math functions that didn’t make it into C++0x):

TR1 (“Technical Report 1”) is a set of proposed additions to the C++0x standard.  Our implementation of TR1 contains a number of important features such as smart pointers, regular expression parsing, containers (tuple, array, unordered set, etc) and sophisticated random number generators.

More information on TR1 can be found at the sites below:

TR1 documentation

Channel 9: Digging into TR1

TR1 slide decks (recommended)

Enjoy, everyone – and thanks, team!

Notes

1. This feature pack requires Visual C++ 2008 Standard or above. The only VC08 edition it doesn’t work with is Express; we’ll support Express in a future release.

2. When I wrote that it would be available “in the first half of 2008,” a number of people seemed to automatically interpret that as code for “maybe around June 31.” We’re not always that bad at shipping, fortunately. :-)

3. Yes, I know that June has 30 days.

Trip Report: February/March 2008 ISO C++ Standards Meeting

[Updated Apr 3 to note automatic deduction of return type.]

The ISO C++ committee met in Bellevue, WA, USA on February 24 to March 1, 2008. Here’s a quick summary of what we did (with links to the relevant papers to read for more details), and information about upcoming meetings.

Lambda functions and closures (N2550)

For me, easily the biggest news of the meeting was that we voted lambda functions and closures into C++0x. I think this will make STL algorithms an order of magnitude more usable, and it will be a great boon to concurrent code where it’s important to be able to conveniently pass around a piece of code like an object, to be invoked wherever the program sees fit (e.g., on a worker thread).

C++ has always supported this via function objects, and lambdas/closures are merely syntactic sugar for writing function object. But, though “merely” a convenience, they are an incredibly powerful convenience for many reasons, including that they can be written right at the point of use instead of somewhere far away.

Example: Write collection to console

For example, let’s say you want to write each of a collection of Widgets to the console.

// Writing a collection to cout, in today’s C++, option 1:

for( vector<Widget>::iterator i = w.begin(); i != w.end(); ++i )
  cout << *i << ” “;

Or we can leverage that C++ already has a special-purpose ostream_iterator type that does what we want:

// Writing a collection to cout, in today’s C++, option 2:

copy( w.begin(), w.end(),
          ostream_iterator<const Widget>( cout, ” ” ) );

In C++0x, just use a lambda that writes the right function object on the fly:

// Writing a collection to cout, in C++0x:

for_each( w.begin(), w.end(),
                []( const Widget& w ) { cout << w << ” “; } );

(Usability note: The lambda version was the only one I wrote correctly the first time as I tried these examples on compilers to check them. ‘Nuff said. <tease type=”shameless”> Yes, that means I tried it on a compiler. No, I’m not making any product feature announcements about VC++ version 10. At least not right now. </tease>)

Example: Find element with Weight() > 100

For another example, let’s say you want to find an element of a collection of Widgets whose weight is greater than 100. Here’s what you might write today:

// Calling find_if using a functor, in today’s C++:

// outside the function, at namespace scope
class GreaterThan {
  int weight;
public:
  GreaterThan( int weight_ )
    : weight(weight_) { }
  bool operator()( const Widget& w ) {
    return w.Weight() > weight;
  }
};

// at point of use
find_if( w.begin(), w.end(), GreaterThan(100) );

At this point some people will point out that (a) we have C++98 standard binder helpers like bind2nd or (b) that we have Boost’s bind and lambda libraries. They don’t really help much here, at least not if you’re interested in having the code be readable and maintainable. If you doubt, try and see.

In C++0x, you can just write:

// Calling find_if using a lambda, in C++0x:

find_if( w.begin(), w.end(),
            []( Widget& w ) { return w.Weight() > 100; } );

Ah. Much better.

Most algorithms are loops… hmm…

In fact, every loop-like algorithm is now usable as a loop. Quick examples using std::for_each and std::transform:

for_each( v.begin(), v.end(), []( Widget& w )
{

  …
  … use or modify w …
  …
} );

transform( v.begin(), v.end(), output.begin(), []( Widget& w )
{
  …
  return SomeResultCalculatedFrom( w );
} );

Hmm. Who knows: As C++0x lambdas start to be supported in upcoming compilers, we may start getting more used to seeing “});” as the end of a loop body.

Concurrency teaser

Finally, want to pass a piece of code to be executed on a thread pool without tediously having to define a functor class out at namespace scope? Do it directly:

// Passing work to a thread pool, in C++0x:

mypool.run( [] { cout << “Hello there (from the pool)”; } );

Gnarly.

Other approved features

  • N2535 Namespace associations (inline namespace)
  • N2540 Inheriting constructors
  • N2541 New function declarator syntax
  • N2543 STL singly linked lists (forward_list)
  • N2544 Unrestricted unions
  • N2546 Removal of auto as a storage-class specifier
  • N2551 Variadic template versions of std::min, std::max, and std::minmax
  • N2554 Scoped allocator model
  • N2525 Allocator-specific swap and move behavior
  • N2547 Allow lock-free atomic<T> in signal handlers
  • N2555 Extended variadic template template parameters
  • N2559 Nesting exceptions (aka wrapped exceptions)

Next Meetings

Here are the next meetings of the ISO C++ standards committee, with links to meeting information where available.

The meetings are public, and if you’re in the area please feel free to drop by.

Stroustrup & Sutter: The Lyrics

Last week’s Stroustrup & Sutter on C++ was a huge amount of fun, and Bjarne and I want to thank everyone who came. It was a record-shattering year, and it’s great to see C++ clearly thriving and growing.

A lot of people requested the (modified) lyrics to the songs we performed (yes, if you missed the event, you missed live music by geeks — imagine, if you will). To those who were there: You can now find the song lyrics at the same web page we gave out that contains the course eval link and the updated slides link. Just go back and you’ll see them, as well as the slides for What Not to Code in the handouts zipfile. Enjoy.

Thanks again for coming, and we hope to see you again next time. (The response to the post-seminar eval question about “would you recommend this course to a colleague” was a humbling 100.0%. Wow. It’s not often I see a pie chart that’s a solid circle. Thank you, and we’re glad you enjoyed it!)

What Not To Code

At Stroustrup & Sutter on C++ this March, one of my sessions will be on "What Not To Code" (submission link). The premise is to try something new I haven’t done before: A session dedicated to making over code nominated by you, the public, in the few weeks before the talk.

In return for your submission, here’s what I’ll do if your entry is selected:

  • Full notes: Whether or not you attend the S&S event, I’ll send you the full talk handouts — not only for your submission, but for all selected submissions — as your thank-you for participating.
  • Participation: If you’re there in the audience, you can participate in the makeover on stage (if you want to, your choice). Oh, and there might be an additional live prize.

I’ll select as many of the submissions as I can, and analyze/critique/improve them during the session, including talking about tradeoffs and alternatives that can make the code clearer, faster, simpler, and/or safer. As the talk blurb concludes:

… you will refresh your sense of elegance and beauty, not to mention old-fashioned performance and robustness and maintainability, so often lacking in the broken code littering today’s bleak postmodern corporate landscape.

So if you’ve seen a friend’s or coworker’s (or your own) code that could use a makeover, please nominate it anytime here. Thanks!

Many Books

When I walk into a Chapters or a Borders, seeing the many shelves of books often recalls the ancient writer’s words about quality vs. quantity, circa 1000 BC:

"To the making of many books there is no end."

So true. Yet that observation predates the printing press… and netnews… and now RSS.

(Yes, I’ve been thinking of managing-down my Google Reader subscriptions again…)

Stroustrup & Sutter on C++: March 3-4, 2008, in Santa Clara, CA, USA

pic

I’m pleased to announce that Bjarne and I are going to have another two-day event co-located with SD West in San Jose, California, this March. Most of the talks are new ones we’ve never given publicly before, along with updated classics that people liked the best in the past. This year, three of my four talks have a strong emphasis on concurrency: making your application manycore-scalable, safe locking, and bleeding-fast lock-free coding.

SD graciously let me publish an extra-discount code for readers of this blog. Here it is… if you register before Feb 8, use the following code to get the early bird price (up to $300 off) plus an extra $50 off any package:

Discount code:  8WSUT  (expires Feb 8)

Here’s a link to the conference site, and their summary:

Stroustrup & Sutter #4

Back with brand new and freshly updated content!

The preeminent super session on the C++ language is back at SD West—and full of new and updated material! Join Bjarne Stroustrup, C++ creator and original implementer, and Herb Sutter, C++ and concurrency guru, for two jam-packed days of new and completely updated courses. The seminar is filled with instructive, revealing and highly pragmatic material, and is structured with both talks and panels—not to mention liberal break times, so that the instructors and attendees can mix, eat and chat together.

In addition to lots of information you can use today, Herb and Bjarne will also reveal important, forward-looking information about what’s coming in the next version of the C++ Standard, C++0x, and related efforts. As key designers of several of the new core features, their personal experiences are invaluable.

Finally, for convenience, below is a cut-and-paste of the session topics and abstracts.

I look forward to seeing many of you in San Jose! Best wishes,

Herb

DAY 1: Monday, March 3

C++0x Overview

Bjarne Stroustrup

We now know the expected contents of the next C++ Standard, which is targeted to be feature-complete in mid-2008 with final text in 2009. This presentation articulates the main principles of the design of C++0x, outlines the ISO C++ standards process, summarizes the new features and libraries, and gives key examples using new features. Major features, such as concepts, the memory model, and major libraries (such as threads and regular expression matching) are covered by other tutorials, so they will be only briefly mentioned here. The focus of this presentation is the various "minor" features, such as the unified initializer syntax (including variable length initializer lists), decltype and the new form of auto, template aliases, nullptr, generalized constant expressions, "strong" enumerations, the new for statement, static assertions, and rvalue references. But a language is far more than a mere list of features: My aim is to show how these features fit together and fit with C++98 features to better support programming techniques. As ever, the ultimate aim of this language design is to allow clearer expression of real-world ideas, leading to better-performing and easier-to-maintain code. Even the "minor features" can significantly affect your programming style.

What Not to Code: Avoiding Bad Design Choices and Worse Implementations

Herb Sutter

Our reality show premise is simple: Friends and coworkers nominate code that they consider poorly "fashioned" and ask the show to make over the victim. Our Code Police swoop in with a deal: We’ll provide up to 15 minutes of public assistance in the form of amusing analyses and insightful improvements, discussing tradeoffs and alternatives that can make the code clearer, faster, simpler, and/or safer… but only on the condition that they allow our instructor (that’s Herb) to ruthlessly critique their existing code, and in some cases throw it out altogether, in front of a live studio audience (that’s you). As members of that interactive audience, you will refresh your sense of elegance and beauty, not to mention old-fashioned performance and robustness and maintainability, so often lacking in the broken code littering today’s bleak postmodern corporate landscape.

How to Design Good Interfaces

Bjarne Stroustrup

So: We have classes, derived classes, virtual bases, templates, const, overloading, exceptions, and a host of other useful language features. How do we use them to produce well performing maintainable code? All too often we get seduced into using powerful language features to write clever (i.e., complicated) code rather than to simplify our interfaces and to make the organization of our code easier to understand. This presentation is a tour of the most useful C++ features from the point of view of how they can be used to express the structure of code and to define interfaces that serve basic needs such as flexibility, early error detection, acceptable compile time, performance, decent error reporting, and maintainability.

How to Migrate C++ Code to the Manycore "Free Lunch"

Herb Sutter

For decades, we enjoyed the "free lunch" of seeing existing applications naturally run faster on new hardware with a faster single CPU core. Computation power is still growing, but in a fundamentally different direction — more and more cores. We can regain the free lunch, but only by building applications in new ways that correctly apply concurrency and parallelism to express lots of latent concurrency that can scale well to a given number of cores but avoids penalizing the application when running on older hardware with one or few cores. This talk addresses the question of how to design new code, and how to migrate existing code, to be multicore/manycore enabled. We will cover best practices for finding and exploiting parallelism in algorithms and data structures, avoiding data structures that harm concurrency, using thread pools and background tasks effectively, and ways to cheat (if not entirely avoid) the specter of Amdahl’s Law. Most code examples will be illustrated using draft standard C++0x syntax, but can be directly translated to popular platforms and concurrency libraries, including Linux, Windows, .NET, and pthreads.

Grill the Experts: Ask Us Anything!

Bjarne Stroustrup and Herb Sutter

This is your opportunity to get "thought leader" answers to your favorite C++ questions! We strongly encourage you to submit your questions in advance, preferably by email or in writing at the beginning of the seminar. Audience questions will also be taken from the floor. Both instructors will answer as many questions as time permits.

DAY 2: Tuesday, March 4

"Best of Stroustrup & Sutter": Concepts and Generic Programming in C++0x

(Update of talk voted “Most Informative” at S&S 2007)
Bjarne Stroustrup

An updated version of the talk voted "Most Informative" at S&S 2007: C++ templates are immensely flexible and the basis of most modern C++ high-performance programming techniques and of many el
egant library designs. They are the key language feature behind the standard library’s algorithms and containers: the STL. However, they can also be tricky to use, cause spectacularly bad error messages when misused, and sometimes require unreasonable amounts of code to express apparently simple ideas. C++0x will address these issues directly, and the key to resolving the problems with templates without loss of flexibility or loss of performance is "concepts." Concepts provide a type system for C++ types and for combinations of C++ types and values. Thus, we are able to provide what feels a lot like conventional type checking for template arguments (including simple and elegant overloading based on template arguments). This presentation explains the notion of concepts and shows how to use concepts to write clearer and more robust generic code using templates. People who can’t wait for C++0x before trying out concepts (and other new C++0x features related to generic programming) can try the proof-of-concept implementation, ConceptGCC.

Safe Locking: Best Practices to Eliminate Race Conditions

Herb Sutter

From many core to web services, writing highly concurrent software is increasingly becoming a mainstream requirement. But how can we best manage shared state, specifically objects in shared memory? We need to chart a safe course between the Scylla of data corruption due to race conditions on one side, and the Charybdis of excessive contention and even deadlock or livelock on the other side. This talk covers these important problems, as well as the simplicity vs. scalability tradeoff and the composability conundrum. It focuses on solutions, from basics like scoped locks through correct use of lock hierarchies, disciplines to associate data with locks, essential guidelines for writing lock-safe code, and other important best practices. Most code examples will be illustrated using draft standard C++0x syntax, but can be directly translated to popular platforms and concurrency libraries, including Linux, Windows, .NET, and pthreads.

Q&A: C++ Design and Evolution

Bjarne Stroustrup

This is a unique opportunity for a "fireside interview" with the creator of C++, moderated by Herb Sutter. After a brief introduction and opening thoughts, Bjarne Stroustrup will take all questions and share thoughtful observations on topics ranging from essential trends affecting software development across languages today, to observations on the strengths and applicability of existing and new languages, to the role of C++ in the 21st century, and more. Attendees are strongly encouraged to submit questions in advance.

Lock-Free Programming in C++—or How to Juggle Razor Blades

Herb Sutter

Concurrent programs increasingly face pressure to avoid locks altogether. This talk focuses on techniques we can sometimes apply to avoid the need for locking and its difficulties. We will cover many effective best practices, from ways to avoid or better manage shared state through to effective use of atomic operations for lock-free coding, including patterns like lock-free mailboxes, low-contention lazy initialization, internally versioned objects, and more. Most code examples will be illustrated using draft standard C++0x syntax and the C++0x memory model, but can be directly translated to popular platforms and concurrency libraries, including Linux, Windows, .NET, and pthreads.

Discussion on Questions Raised During the Seminar

Herb Sutter and Bjarne Stroustrup

This panel is set aside for follow-up comments and discussion on issues that are raised during the seminar. During the other talks and panels, or during between-session chats, questions often come up that the instructors want to research. Some of the resulting information will be of general interest, and this final panel provides the needed convenient opportunity to promulgate it to everyone.