views:

199

answers:

4

I have been a C programmer for many years and my favorite "debugger" has always been the printf() function - I only resort to visual studio's debugger when absolutely forced and so have never been very proficient in using it. Recently I have had to modify a program from C to C++ (although of course printf still works fine) and and parts of the program are now farmed out in to multiple threads (one for each core on a multicore machine) to make the program run faster. Now i will no doubt come up against awkward multi-thread related bugs like deadlocks and I wonder what debugging methodology I can turn to. Does visual studio (2008) have everything I could reasonably need to help me resolve thread related bugs? Should I take some time out now to learn how to use some third party debugger? Could I solve most problems using my good old printf?

Could I for example write code which, if kept waiting on entry to a critical section would print something like "Thread X waiting to enter ... but blocked because its being used by thread Y"?

A: 

If you could port your project to Linux, Valgrind (especially the 'helgrind' tool) would do exactly what you ask. http://valgrind.org/

Benjamin
+10  A: 

Visual Studio supports thread debugging to some extend. Via the Threads Window you can select threads, suspend and resume threads etc. When you switch between threads the Call Stack Window is updated accordingly so you can inspect what each thread is doing. You may also restrict breakpoints to specific threads.

If you want an alternative WinDbg (which is part of the free Debugging Tools for Windows package from Microsoft) offers lots of options as well but with a slightly more esoteric user interface.

As for using printf, there's the problem of synchronizing output. If you don't do it you output will most likely be gibberish. If you do synchronize it you basically change the concurrency of the application, which may or may not affect the problem you're trying to solve.

Brian Rasmussen
A: 

I'm not sure if this is exactly what you are asking, but, To help in debugging, you can write code that gives each thread a "name", so that debug messages printed to the debug window, (or a log file or whatever) include that thread "name" along with whatever other info you prescribe. The code below is in C# but this is available even in unmanaged C++

  Thread T = new Thread(RunSchedule);
  T.Name = "Scheduler";    // <=== Thread given a name here... 
  T.Start();
Charles Bretana
This can be achieved in "pure" native C and C++ by using the WIN32 API function void SetThreadName( DWORD dwThreadID, LPCSTR szThreadName). Those names should also show up in the VS debugger (I haven't checked this).
rstevens
A: 

Intel provides several tools to find out threading-related issues: data races, deadlocks, performance penalties. These tools are: Intel Thread Checker, Intel Thread Profiler.

Vova