简体   繁体   中英

Stepping through a multithreaded application with GDB

1st foray into using pthreads to create a multithreaded aplication

I'm trying to debug with gdb but getting some strange unexpected behaviour

Trying to ascertain whether its me or gdb at fault

Scenario:

  1. Main thread creates a child thread.
  2. I place a breakpoint on a line in the child thread fn
  3. gdb stops on that breakpoint no problem
  4. I confirm there are now 2 threads with info threads
  5. I also check that the 2nd thread is starred, ie it is the current thread for gdb s purposes
  6. Here is the problem, when I now hit n to step through to the next line in the thread fn, the parent thread (thread 1) simply resumes and completes and gdb exits.

Is this the correct behaviour?

How can I step through the thread fn code that is being executed in the 2nd thread line by line with gdb ?

In other words, even though thread 2 is confirmed as the current thread by gdb , when I hit n , it seems to be the equivalent of hitting c in the parent thread, ie the parent thread (thread 1) just resumes execution, completes and exits.

At a loss as to how to debug multiple threads with gdb behaving as it is currently

I am using gdb from within emacs25, ie Mx gud-gdb

What GDB does here depends on your settings, and also your system (some vendors patch this area).

Normally, in all-stop mode, when the inferior stops, GDB stops all the threads. This gives you the behavior that you'd "expect" -- you can switch freely between threads and see what is going on in each one.

When the inferior continues, including via next or step , GDB lets all threads run. So, if your second thread doesn't interact with your first thread in any way (no locks, etc), you may well see it exit.

However, you can control this using set scheduler-locking . Setting this to on will make it so that only the current thread can be resumed. And, setting it to step will make it so that only the current thread can be resumed by step and next , but will let all threads run freely on continue and the like.

The default mode here is replay , which is basically off , except when using record-and-replay mode. However, the Fedora GDB is built with the default as step ; I am not sure if other distros followed this, but you may want to check.

Yes, this is correct behaviour of gdb. You are only debugging currently active thread, other threads are executing normally behind the scenes. Think about it, how else would you move other threds?

But your code has a bug. Your parent thread should not exit before child thread is done. The best way to do this is to join child thread in the main thread before exiting.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM