Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will debugging change the behavior of a multi-thread C++ program?

I am working on a multi-threaded C++ program which deals with a lot of synchronization issues. I am using Visual Studio 2008.

The run-time behavior of my program (the order in which statements are executed across threads) seems to change when I debug it using breakpoints. Can this be explained? What is the concept at play here? I would expect the order of execution to remain the same.

Second question - if Thread1 is blocked by, say, a wait function call. Thread2 has statements waiting to be executed, in ready state. Is there any situation where the program will wait for Thread1 to proceed rather than giving execution to Thread2? I have removed all dependencies between the two thread and ensured that Thread2 is not waiting for any resource.

Appreciate the responses.

like image 583
Shailesh Tainwala Avatar asked Jul 09 '12 06:07

Shailesh Tainwala


People also ask

Why it is difficult to debug multi threaded programs?

Parallel processing using many threads can greatly improve program performance, but it may also make debugging more difficult because you're tracking many threads. Multithreading can introduce new types of potential bugs.

Is C good for multithreading?

Can we write multithreading programs in C? Unlike Java, multithreading is not supported by the language standard. POSIX Threads (or Pthreads) is a POSIX standard for threads.

What is multithreaded programming in C?

Multithreading is a model of program execution that allows for multiple threads to be created within a process, executing independently but concurrently sharing process resources. Depending on the hardware, threads can run fully parallel if they are distributed to their own CPU core.


1 Answers

This article on multithreaded debugging techniques makes a few good summary points on the topic:

Multithreaded bugs may not surface when running under the debugger. Multithreading bugs are very sensitive to the timing of events in an application. Running the application under the debugger changes the timing, and as a result, may mask problems. When your application fails in a test or worse, the customer environment, but runs reliably under the debugger, it is almost certainly a timing issue in the code.

...and more to your specific latter question, it's important to understand that--in the majority case--the operating system is free to interrupt the execution of any of your threads whenever it pleases, even ones that are "ready" to execute.

like image 54
reuben Avatar answered Sep 28 '22 03:09

reuben