Wednesday, July 3, 2013

Tip: we are not alone

This is a technical tip that can help when we join a project and something goes wrong but all the code seems clear. Happen to me ones that I was executing two print of the same variable within a distance of few lines and no line was modifing this variable. While I was expecting the print to be the same, I was continuosly get two different values. I spent a lot of time trying to find if was a memory corruption but in the end the issue was due to thread scheduling that overwrites the variable. When we debug, we can have the impression that a single thread is present, but most of the time is not. Even worse if when (as in this example), debugging the program will make the issue disappear due to changing in timing. So basically, if you suspect that multiple threads can run because you don't know perfectly the code, it's always a good idea to instrument your debugging printf with the thread id of the process. In this way you will see more clearly which thread is writing on the console making you understand better how the threads are scheduled.

No comments:

Post a Comment