gdbWatchPoint

Debugging multithreaded programs in GDB

Last updated 22nd Jun 2022

In this episode, our guest contributor is Satabdi Das, Software Development Engineer at AWS. Satabdi is an expert at developing and debugging complex software systems in C++. She is also a speaker at C++ community events. Over to her!

In this tutorial, I am going to show you a few GDB commands for debugging multi-threaded programs. Running GDB on C++ programs with multiple threads is difficult, but these commands are going to give you some visibility into the state of your program and help you debug multi-threaded programs. When I run a multi-threaded program on GDB, I’d like to see the thread information. I am going to use the following commands to get the information about the existing threads:

 info threads

And the output is going to look like the following:

Debugging multithreaded programs image 1

The star to the left of thread number 2 indicates that this is the current thread. I haven’t specified any arguments to this command. So it displays information about all the threads. You can specify the list of threads that you want to see. For example, I can get information for threads 1 and 2 using the command info threads 1 2 

Debugging multithreaded programs image 2

Sometimes I want to switch between threads and check what a specific thread is doing. I am going to use the command thread 1 to switch to thread number 1.

Debugging multithreaded programs image 3

Let’s execute the next line on GDB.

Debugging multithreaded programs image 4

Note that gdb switched to a different thread. This can be annoying when you want to trace the execution for a particular thread. You can use the command set scheduler-locking on

And now GDB is going to run only the current thread.
Debugging multithreaded programs image 5

Next, I am going to set a thread-specific breakpoint. I am going to set a breakpoint on line 16 for the current thread using the command  b 16 thread 4. Since I have set the breakpoint only for this thread, GDB is not switching between threads.

Debugging multithreaded programs image 6

The last command I am going to show you is to apply a certain command to a group of threads. For example, I want to print the backtrace of all the threads and I am going to use the command thread apply all bt

Debugging multithreaded programs - image 7

That’s all I wanted to share with you in this tutorial. Hope you’ve learnt something new about GDB today.

Don't miss the next GDB tutorial: sign up to the gdbWatchPoint mailing list below.
Get tutorials straight to your inbox
Become a GDB Power User. Get Greg's debugging tips directly in your inbox every 2 weeks.

A dedicated resource to learn about debugging in GDB by industry leader in debugging and founder of Undo

Meet Greg