Step 3. Test for Correctness: Detecting and Fixing Threading Errors

Whenever you make code changes to an application, you open the door to the possibility of introducing bugs. Adding code to a serial application in order to generate and control multiple threads is no exception. As I alluded to before, the execution of threaded applications may or may not reveal any problems during testing. You might be able to run the application correctly hundreds of times, but when you try it out on another system, errors might show up on the
new system or they might not. Even if you can get a run that demonstrates an error, running the code through a debugger (even one that is thread-aware) may not pinpoint the problem, since the stepwise execution may mask the error when you are actively looking for it. Using a print statement-that most-used of all debugging tools-to track values assigned to variables can modify the timing of thread interleavings, and that can also hide the error.

天呀,我们在调试中最常用的print大法,可能会改变线程运行timing时序上的相互关系,以至于隐藏一个错误........

The more common threading errors, such as data races and deadlock, may be avoided completely if you know about the causes of these errors and plan well enough in the Design and Implementation step to avoid them. However, with the use of pointers and other such indirect references within programming languages, these problems can be virtually impossible to foresee. In fact, you may have cases in which the input data will determine if an error might
manifest itself. Luckily, there are tools that can assist in tracking down threading errors. I've listed some of these in Chapter 11.

Even after you have removed all of the known threading bugs introduced by your modifications, the code may still not give the same answers as the serial version. If the answers are just slightly off, you may be experiencing round-off error, since the order of combining results generated by separate threads may not match the combination order of values that were generated in the serial code.

More egregious (惊人的;过分的;恶名昭彰的) errors are likely due to the introduction of some logic error when threading. Perhaps you have a loop where some iteration is executed multiple times or where some loop iterations are not executed at all. You won't be able to find these kinds of errors with any tool that looks for threading errors, but you may be able to home in on the problem with the use of some sort of debugging tool. One of the minor themes of this book is the typical logic errors that can be introduced around threaded code and how to avoid these errors in the first place.

With a good solid design, you should be able to keep the number of threading or logic errors to a minimum, so not much verbiage (冗词,空话,废话)is spent on finding or correcting errors in code.

posted on 2010-09-11 09:28  胡是  阅读(249)  评论(0编辑  收藏  举报

导航