MSDN Magazine - October 2008 - (Page 104) ConCurrenCy Ha zards Solving 11 Likely Problems In Your Multithreaded Code Joe duffy Concurrency is everywhere. Server-side programs have long had to deal with a fundamentally concurrent programming model, and as multicore processors become more commonplace, client-side programs will have to as well. Along with the addition of concurrency comes the responsibility for ensuring safety. In other words, programs must continue to achieve the same level of robustness and reliability in the face of large amounts of logical concurrency and ever-changing degrees of physical hardware parallelism. Correctly engineered concurrent code must live by an extra set of rules when compared to its sequential counterpart. Reads and writes from memory and access to shared resources need to be regulated using synchronization so that conflicts do not arise. Additionally, it often becomes necessary for threads to coordinate to get a certain job done. This article discusses: • Fundamental concurrency concepts • Concurrency problems and mitigations • Patterns for achieving safety • Cross-cutting concepts As a direct result of these additional requirements, it becomes nontrivial to ensure that threads are continually making consistent and adequate forward progress. Synchronization and coordination deeply depend on timing, which is nondeterministic and hard to predict and test for. What makes these attributes difficult is simply that it requires a mindset shift. There isn’t a single API that you can learn or a snippet of code to copy and paste. There really is a fundamental set of concepts that you need to learn and become comfortable with. It’s likely that certain languages and libraries can hide some concepts over time, but if you’re doing concurrency today, you won’t have that luxury. This article describes some of the more common challenges to be aware of and presents advice for coping with them in your software. I’ll start by looking at the kinds of things that often go wrong in concurrent programs. I call these “safety hazards” because they are so easy to stumble upon and because their consequences are typically quite undesirable. These hazards cause your programs to break by either crashing or corrupting memory. Data Races Technologies discussed: Multithreading, .neT Framework 104 msdn magazine A data race—or race condition—occurs when data is accessed concurrently from multiple threads. Specifically, it happens when one or more threads are writing a piece of data while one or more threads are also reading that piece of data. This problem arises be-
For optimal viewing of this digital publication, please enable JavaScript and then refresh the page. If you would like to try to load the digital publication without using Flash Player detection, please click here.