|
Spaces home Sutter's MillProfileFriendsBlog | ![]() |
|
|
4/5/2008 Moved to http://herbsutter.wordpress.comEffective immediately, this blog has moved to WordPress:
I like Live Spaces, and I really hate moving a blog, but unfortunately the comment spam is out of control and I just can't keep up with the tools available to manage it here -- other than accepting a blog with no comments at all, which I'm unwilling to do. Your comments are too valuable to give up.
Fortunately, the new blog location retains copies of all past posts and comments -- minus the spam -- thanks to Wei Wei's wonderful Live Space Mover script. Thanks again, Wei Wei, for your support over the weekend in tweaking the script to work with my site.
So please update your bookmarks and feeds to the new blog, and please direct your new comments there as well. I've now disabled further comments here just to keep new spam out of this mothballed space, but I'll otherwise leave this up intact until people find the new location.
See you there!
3/29/2008 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 Mar 1. 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 consoleFor example, let's say you want to write each of a collection of Widgets to the console.
Or we can leverage that C++ already has a special-purpose ostream_iterator type that does what we want:
In C++0x, just use a lambda that writes the right function object on the fly:
(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() > 100For 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:
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:
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:
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 teaserFinally, 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:
Gnarly. Other approved features
Next MeetingsHere 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. 3/28/2008 Concurrency Interview with DevXI recently spent an hour on the phone to talk concurrency with DevX's Alexa Weber Morales. Part 1 of that interview just went live on the web, and focuses mostly on what concurrency and parallelism are, how to take advantage of multicore chips, and whether concurrency will ever be really accessible to mainstream developers. The site seems to be having intermittent problems displaying the pages; just hit the link a few more times if it doesn't work right away. Disclaimer: I am not responsible for the article title (yikes! "whisperer"?! my goodness gracious!) and the intro blurb vastly overstates my role (Alexa is being way too kind). But it is true that it's important for us-the-industry to bring concurrency to the mainstream in a grokkable way, as we have already successfully done with OO and GUIs in the past. 3/12/2008 New Course Available: Effective ConcurrencyMany of you have kindly sent mail about my Effective Concurrency columns and asking when there'll be a course. Well, I'm happy to announce that the answer is: May 19-21, 2008. Here's the brief information (more details below):
Note on class size limit and possible waitlist: There is a hard limit on attendance at this first one (really). But if the registration site says you'll get waitlisted, don't give up: Go ahead and sign up anyway because we may be able to put together a second installment of the seminar a week or two later if there's enough interest. Finally, here's a summary of what we'll cover during the three days.
I hope to get to meet some of you here in the Seattle area! Effective Concurrency: Super Linearity and the Bigger MachineThe latest Effective Concurrency column, "Super Linearity and the Bigger Machine", just went live on DDJ's site, and will also appear in the print magazine. From the article:
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):
3/10/2008 Stroustrup & Sutter: The LyricsLast 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!) 2/1/2008 How parallelism demos are usefulIn "Break Amdahl's Law!", I described ways to enable scalable applications, and wrote in part:
Just to be clear, in the first sentence above I didn't mean to say that the standard demos are useless -- far from it (see below). This was intended to be a challenging call to action to not be satisfied with demos alone, but for us as an industry to imagine and develop compelling mainstream end applications that are multicore- and manycore-scalable. (To make that clearer, I'm going to ditch and rewrite the first sentence above for the Effective Concurrency book.) The standard demos are indeed important -- not only as proofs of concept, that the technology really does enable scalable parallel code, but at least as importantly as helpful tools in helping us to understand how a given parallel technology or runtime works. To understand concurrency mechanics/characteristics
To illustrate a path to future applications
Yes, demos are usefulMy point in the original quote above (which I see I could have stated more clearly) was simply this: Once we've achieved the demos, we shouldn't sit back and declare victory. The demos aren't the end goal; we still need the applications. Concurrency demos are useful to help prove a technology can scale and to understand how it works, and some of them show potentially fruitful and exciting paths to real and compelling manycore-exploiting applications, but it's still up to us as an industry to continue to imagine and build those applications. I believe that we can and will. 1/30/2008 Effective Concurrency: Going Superlinear
The latest Effective Concurrency column, "Going Superlinear", just went live on DDJ's site, and will also appear in the print magazine. From the article:
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):
1/28/2008 What Not To CodeAt 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:
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:
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! 1/25/2008 Many BooksWhen 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:
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...) 1/22/2008 Stroustrup & Sutter on C++: March 3-4, 2008, in Santa Clara, CA, USAI'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:
Here's a link to the conference site, and their summary:
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 3C++0x OverviewBjarne 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 ImplementationsHerb 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 InterfacesBjarne 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) 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 elegant 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 ConditionsHerb 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 EvolutionBjarne 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 BladesHerb 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 SeminarHerb 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. 1/17/2008 Effective Concurrency: Break Amdahl's Law!The latest Effective Concurrency column, "Break Amdahl's Law!", just went live on DDJ's site, and will also appear in the print magazine. From the article:
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):
1/1/2008 GotW #88: A Candidate For the "Most Important const"A friend recently asked me whether Example 1 below is legal, and if so what it means. It led to a nice discussion I thought I'd post here. Since it was in close to GotW style already, I thought I'd do another honorary one after all these years... no, I have not made a New Year's Resolution to resume writing regular GotWs. :-) JG QuestionsQ1: Is the following code legal C++?
A1: Yes.This is a C++ feature… the code is valid and does exactly what it appears to do. Normally, a temporary object lasts only until the end of the full expression in which it appears. However, C++ deliberately specifies that binding a temporary object to a reference to const on the stack lengthens the lifetime of the temporary to the lifetime of the reference itself, and thus avoids what would otherwise be a common dangling-reference error. In the example above, the temporary returned by f() lives until the closing curly brace. (Note this only applies to stack-based references. It doesn't work for references that are members of objects.) Does this work in practice? Yes, it works on all compilers I tried (except Digital Mars 8.50, so I sent a bug report to Walter to rattle his cage :-) and he quickly fixed it for the Digital Mars 8.51.0 beta). Q2: What if we take out the const... is Example 2 still legal C++?
A2: No.The "const" is important. The first line is an error and the code won't compile portably with this reference to non-const, because f() returns a temporary object (i.e., rvalue) and only lvalues can be bound to references to non-const. Note: Visual C++ does allow Example 2 but emits a "nonstandard extension used" warning by default. A conforming C++ compiler can always allow otherwise-illegal C++ code to compile and give it some meaning -- hey, it could choose to allow inline COBOL if some kooky compiler writer was willing to implement that extension, maybe after a few too many Tequilas. For some kinds of extensions the C++ standard requires that the compiler at least emit some diagnostic to say that the code isn't valid ISO C++, as this compiler does. I once heard Andrei Alexandrescu give a talk on ScopeGuard (invented by Petru Marginean) where he used this C++ feature and called it "the most important const I ever wrote." And this brings us to the Guru Question, which highlights the additional subtlety that Andrei's code deftly leveraged...
Guru QuestionQ3: When the reference goes out of scope, which destructor gets called?A3: The same destructor that would be called for the temporary object. It's just being delayed.Corollary: You can take a const Base& to a Derived temporary and it will be destroyed without virtual dispatch on the destructor call. This is nifty. Consider the following code:
Does this work in practice on real compilers? Yes: Every compiler I have access to calls the correct Derived destructor, including even ancient Borland 5.5 and Visual C++ 6.0 (and Digital Mars, though DM calls the destructor at the wrong time, as noted above). Andrei leverages this subtlety (of course) in his ScopeGuard implementation to avoid making the implementation classes' destructors virtual at all, which is okay in that case because those classes otherwise have no need for one.
Updates:
12/11/2007 Effective Concurrency: Use Lock Hierarchies to Avoid Deadlock The latest Effective Concurrency column, "Use Lock Hierarchies to Avoid Deadlock", just went live on DDJ's site, and will also appear in the print magazine. From the article:
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):
12/7/2007 Let's Be Thoughtful Out ThereI knew Hanlon's Razor: "Never attribute to malice that which can be adequately explained by stupidity." And the variants attributed to Heinlein, described on the same page as adding "... but don't rule out malice." or "... but keep your eyes open." But I only just now came across Grey's Law, which follows the flavor of Clarke's Third Law: "Any sufficiently advanced incompetence is indistinguishable from malice." One example that irritates me too is focus-stealing popups. Grr, no, I didn't mean that enter key to select "Reboot", I was just finishing a paragraph or writing a space. Please, Mr. Callous Software Developer, just leave me alone! I don't care how important you think your application is -- it's never important enough to pop up on top without warning. No. Bad developer. Down. I said down. Stay. As a counterexample, I really like how Windows handles the "are you sure you want to run this application?" dialog. Not only does it not steal focus... even better, it ignores the first mouse click when it gets focus. That's right, if the window is visible but not active, and you click on the "Run" button, it doesn't also push Run -- it merely makes the window active. Then if you hit Run again, it runs. Yes! Good developer! To paraphrase Hill Street Blues: Let's be thoughtful out there. 12/5/2007 TR1 in (Free) VC++ ExpressA few weeks ago I blogged about the VC++ update we plan to ship in the first half of next year, which includes extensive additions to MFC as well as TR1. TR1 is the first set of library extensions published by the C++ committee, nearly all of which have also been adopted into the next C++ standard, C++0x. The update will be available to users of Visual Studio 2008 Standard and above in the first half of 2008... but it will not be immediately available to users of our free C++ compiler, Visual C++ Express. In response to that announcement, an anonymous commenter asked:
Answer: Yes. The current goal is to include the MFC Update & TR1 bits in the first service pack to Visual Studio 2008, including the Express Edition, but the final decision on this packaging and the timing of SP1 haven't been firmed up yet. When they are, I'll mention it here. 12/1/2007 Parallel Computing Releases at MicrosoftFor those of you who may be interested in concurrency for Microsoft platforms, and .NET in particular, I'm happy to report some fresh announcements:
PFX is for .NET concurrency development, but of course we are (and personally I am) working on native development tools, including for C++ specifically, that are at least as exciting. Stay tuned here for future news. In the meantime, enjoy these bits and the resources and discussion on the Parallel Computing developer center and forums. The Concurrency Land Rush: 2007-20??Every time that we experience a "wave" in which the industry takes a programming paradigm that's been growing in a niche, and brings it to the mainstream, we go through similar phases:
We (the software industry) have done it all before for technologies like OO and GUIs, and now we're going to do it for concurrency. Starting in 2005, companies started to talk concurrency and to launch internal efforts. But only this year, in 2007, has our industry formally entered the concurrency wave's land rush phase by starting to field real products and preview releases. We're starting to see initial steps toward candidate mainstream-accessible products in releases like Intel's Threading Building Blocks and Software Transactional Memory prototype compiler, and Microsoft's just-announced and downloadable .NET Parallel Extensions (PFX) including CTP-level support for Parallel LINQ (PLINQ) and the Task Parallel Library. True, the concurrency landscape has lots of existing tools. So did OO (e.g., Simula) and GUIs (e.g., the Win16 C API) long before they became widely accessible to developers in general. Concurrency's "Simulas and Win16s" include Thread classes and OpenMPI for doing work asynchronously, to OpenMP for fast parallel computation, to some pre-fab lock-free container classes, to limited race detectors and very basic thread profilers. But today's tools are still what you'd expect to see in a niche market: Good enough for highly-trained experts to deliver real products, but not easy enough and not integrated enough across the software stack and tool chains to be broadly adopted by mainstream developers. Just as the OO mainstream land rush was fueled by new and updated tools like Smalltalk and Objective-C and C++ and Java offerings, and the GUI land rush was fueled by MFC and OWL and Cocoa and Visual Basic and Delphi, we're starting to see new and existing companies bringing lots of new and updated offerings across the entire software stack and ecosystem. Expect to see lots of new and updated/extended offerings of:
These are the just beginning. Much more will come, from those same companies and others. Expect at least dozens of major product announcements and releases across the industry, before the toolset expansion phase is fully underway and approaching some maturity. We the industry have undertaken to bring concurrency to the mainstream, and as with OO and GUIs it will take multiple years, and multiple major releases, across the industry on all platforms. As I write this, Seattle's first snowfall of the season is gently descending outside my window. It readily puts one in mind of Frost: We have promises to keep, and miles to go before we sleep. 11/30/2007 Concurrency Town Hall: On the web, this Monday, December 3Earlier this fall, James Reinders and I each gave concurrency webcast as part of Intel's fall webcast series. On Monday, James and I are going to be following that up with a virtual Town Hall panel discussion on concurrency, with Dr. Dobb's editor Jon Erickson as our moderator. Should be cool. And you are invited to attend. Here are the coordinates:
I expect that most people will be watching the event via the live simulcast on Second Life Cable Network. Use that if you're not a Second Life member, or if you are a member but can't get in there because the SL servers are expected to reach their maximum capacity for a single event. There's also a network breakfast before the town hall portion. Here's the full description, as it appears on Intel's site:
|