如何一次将gdb调试限制为一个线程

Yog*_*rma 21 gdb pthreads

我想通过控制哪些线程执行时调试多线程程序.我正在使用C++和gdb.除主线程之外我有两个线程(对于示例程序),我想调试一个线程,同时保持另一个线程停止.

这是我写的示例程序:

#include <iostream>
#include <pthread.h>
#include <stdlib.h>

#define NUM_THREADS 2

using namespace std;

void * run (void *) {
  for (int i = 0; i < 3; ++i) {
    sleep(1);
    cout << i << " " << pthread_self() << endl;
  }
  pthread_exit(NULL);
}

int main (int argc, char** argv) {
  cout << "Start..." << endl;
  int rc;

  pthread_t threads[NUM_THREADS];
  for (int i = 0; i < NUM_THREADS; ++i) {
    rc = pthread_create(&threads[i], NULL, run, NULL);
    if (rc) {
      cout << "pthread_create returned error: " << rc << endl;
      exit(-1);
    }
  }
  pthread_exit(NULL);

}
Run Code Online (Sandbox Code Playgroud)

我运行gdb并将断点设置为sleep(1).然后我运行程序.我得到三个线程(线程2和3是pthreads),程序在线程2(等待sleep(1)).现在,我希望将线程3保留在任何地方,并继续单步执行线程2(通过c在gdb中执行).

我试过的是set scheduler-locking on,但它似乎没有像我预期的那样工作.我在线程2,我set scheduler-locking on,continue几次(到目前为止好,我仍然在线程2),切换到线程3 set scheduler-locking on,continue以及由于某种原因,我早在螺纹2 ......当我不应该(根据我的理解).有什么我想念的吗?

小智 9

看起来调度锁定仅在单步或下一步时有用.一旦你继续你当前的线程,它们都会运行,并且下一个到达断点的线程将获取提示.至少,这是我对手册的解释:

http://ftp.gnu.org/old-gnu/Manuals/gdb-5.1.1/html_node/gdb_39.html

因此,一旦你进入线程3,其他线程就会被停止,只要你继续下一步,它们就不会运行.但是一旦你继续,它们都会运行,并且下一个线程(在你的例子中为2)触及睡眠中的断点(1)将获取提示.

也许让所有线程都进入睡眠状态,但是一次只能继续其中一个线程.

  • 使用“set Scheduler-locking on”据说与操作系统相关。不过,似乎在我的系统上运行良好(Linux 4.4.0 内核、gdb 7.11.1、Ubuntu 16.04) (2认同)

Rah*_*ram 7

正如TazMainiac所说,调度程序锁定对于单步执行非常有用,但"模式"必须设置为"步进".

set scheduler-locking step
Run Code Online (Sandbox Code Playgroud)

您可以参考TazMainiac提供的链接,其中提到了相同的内容:

http://ftp.gnu.org/old-gnu/Manuals/gdb-5.1.1/html_node/gdb_39.html

步进模式优化单步执行.它通过在您踩踏时抢占当前线程来阻止其他线程"抓住提示".