c++ - 调试器看到的输出线程 ID

标签 c++ multithreading gcc gdb

我正在使用 GCC 4.4.5 和 GDB 7.2 开发多线程 C++ 应用程序。 目前,我有四个线程。每一个都以一种或另一种形式与 CAN 总线交互,读取、写入、轮询或处理消息。

为了确定哪个线程在做什么,我决定将线程 ID 添加到日志消息中。 在我的日志记录功能中,我有以下代码:

// This is for outputting debug messages
void logDebug(string msg, thread::id threadId[ = NULL]) {
    #ifdebug _DEBUG
    threadState.outputLock->lock();
    if (threadId != NULL)
        cout << "[Thread #" << threadId << "] ";
    // The rest of the output
    threadState.outputLock->unlock();
    #endif
}

这是应用程序的(调试)输出:

[Thread #3085296768] [DEBUG] [Mon Jun 17 10:18:45 2019] CAN frame was empty or no message on bus...
         ----------

这就是 GDB 告诉我的:

Thread #3 7575 [core: 0] (Suspended: Breakpoint)
          ----

为什么调试器向我提供来自应用程序的不同信息(线程 ID/编号),并且有没有办法在应用程序中输出与调试器告诉我的相同的信息?

预期的行为是线程 ID 相同。

编辑: 我忘了添加一些可能重要的信息。 我正在交叉编译一个由 POWERPC 芯片驱动的嵌入式设备,运行 Debian Wheezy 的衍生版本。

最佳答案

您可以使用以下系统调用从应用程序中获取线程 ID:syscall(SYS_gettid)

从那里您可以通过以下任一方式设置线程名称:

  • 直接把名字写在/proc/PID/task/TID/comm
  • 使用pthread函数int pthread_setname_np(pthread_t thread, const char *name)

然后在 GDB 中,您可以使用 info threads 命令轻松匹配给定的线程名称、其 Linux TID 和 GDB 线程 ID。

希望这对您有所帮助。

关于c++ - 调试器看到的输出线程 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56627447/

相关文章:

c++ - 递归到达非空二叉搜索树

android - 为什么这个线程会卡住 UI

java - JNI - Java 在 native 线程完成执行之前退出

c++ - Boost Thread - 创建一个没有 join() 的线程

通过 macOS 终端编译, fatal error : stdio. h: No such file or directory

c - 出现错误 : expected declaration specifiers or '...' before string constant

c++ - 如何反汇编 Pro*C/C++ 程序?

c++ - clang osx march=native 没有优化的大约 1/3rd 速度

c++ - 参数列表中没有 "const"无法编译 lambda

c++ - 错误 : `#elif with no expression` - happens only on Windows