【问题标题】:Output thread IDs as seen by debugger调试器看到的输出线程 ID
【发布时间】:2019-06-17 08:24:04
【问题描述】:

我正在使用 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 的?
  • 通过执行this_thread::get_id()获取日志中的线程ID;

标签: c++ multithreading gcc gdb


【解决方案1】:

您可以使用以下系统调用从您的应用程序中获取线程 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。

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多