Search code examples
c++multithreadingvisual-studiovisual-studio-2022visual-studio-debugging

When single stepping (Step Over) through a multithreaded C++ application in Visual Studio, do all threads execute in lockstep in parallel?


Suppose you're debugging an application with 2 threads, Thread A and B, and you have a breakpoint set somewhere that is reachable by A. You select A as the active thread and run until it hits that breakpoint and execution stops for all threads.

At this point, if you were to hit "Step Over" (F10), do A and B both progress by one line of code 1? Or do all threads single-step forward?

What if instead, you hit "Step Into" (F11) or "Step Out" (Shift + F11) or "Continue"? What do the inactive thread(s) do?

I ask because, sometimes, it seems like while I single-step through code in the active thread, the other (left unfrozen) threads execute one or multiple steps (or possibly however many instructions they can execute in the time it takes the active thread to run until it reaches the next LoC), which is undesirable. But this might be the intended behavior, which is why VS allows you to Freeze/Thaw threads - so that you can manage the lock-stepping yourself to have granularity in thread execution order.

1: I don't think Step Over always single steps through the next line of code. Sometimes it steps through the next assembly instruction.


Solution

  • When you hit a breakpoint in VS, all threads for the application you are debugging are paused at whatever point they happen to be at. When you click "step over/into" in the active thread, all other threads will be unpaused and will execute as many instructions as possible, until the active thread reaches the next breakable line.

    This could be one instruction for one thread, and multiple for another; this really depends on how long it takes to step over the instruction in the thread you were debugging.

    You cannot "lock step" each thread to each other, short of putting breakpoints on the next line of code for all the active threads.

    You can, in VS, select the threads from a dropdown to see what each is currently paused on.