In this article we will discuss how to debug multi-threading C++ application using gdb debugger.

Compiling Multi-threaded Code using g++ with Debug Info

To compile code in debug mode in gcc/g++ we need to use option “-g” .
Also in Linux to compile multi threading we need to include pthread library option i.e. “-pthread”.

Let see how to compile a c++11 thread code (sample.cpp) with debug symbol i.e.

Now start the debugging.

How to List all active threads

To list all the active threads use command,

“info threads”

For example,


Each row represents a thread and contains info like thread id and current frame.
So, like in above example we have 4 active threads. Each thread has an assigned ID, which is visible in first column.

How to Check Stack trace of threads

In non multi threading applications there is only one thread i.e. main function. Therefore, to check the stacktrace we use command “bt”.
But in multi threading applications, as there are many threads and each threads has its own stack.
But “bt” command will display the stack trace of current active thread only. Now what if want to inspect stacktrace of all the threads at same point ?

To display the stack trace of all the threads use following command

It will display the stack trace of all the active threads.


The command “thread apply applies the specified command to specified thread ID. Also, you can specify “all” instead of thread ID to apply the command to all threads.

To display the stack trace of current thread only use command “bt” i.e.

It will show the stacktrace as follows,

Now how to inspect stacktrace of different threads?

How to Switch between threads while debugging

To switch between different threads to inspect their stack trace while debugging use following command,

For example,

It will switch the debugger to thread 2. Now if use will type “bt” command then it will show the stack trace of thread 2.

Click Here to Subscribe for more Articles / Tutorials like this.