Debugging Multi-threaded Programs
Debugging multi-threaded programs is not easy. Here are some
guidelines. If you follow these guidelines, you will spend much less time
debugging.
- Use asserts. If you've never used asserts before, now is a good time
to learn how to use them. Asserts allow you to check that something
you believe is true is actually true. Look at the example code that is
provided to see how asserts are used. You can also read what MSDN
Online has to say about assert.
Asserts are great.
- Check the return value of every function that you call to make sure that
it was successful. The sample code does this, and so should you.
It's usually bad style to check the return value only with an assert, but
feel free to follow my lead and do this. You will catch a lot of
errors this way.
- Unlike in single-threaded debugging, print statements are usually more
useful than trying to step through the code. Well-placed printfs will allow
you to track down most bugs quickly. If your program produces a lot of
output (i.e. more than fits on the screen), you can change the size of the
console window by clicking on the icon in the upper-left corner of the
console window and selecting properties, and then change the Screen Buffer
Size (Height) to be 1000.
- You should step through code only as a last resort. If you are
stepping through code when multiple threads are active, then you should
suspend the other threads until you are done stepping through the
code. Otherwise, the debugger will jump back and forth between
threads, which is very confusing. You can do this in MSVC++ by
selecting Debug->Threads and then clicking on and suspending each thread
other than the one you are debugging. When you are ready to continue
you should resume the other threads in the same way.
Good luck!